repoman / repoman / commands.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
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
# Copyright 2009-2012 Edlund A/S
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''
Commands exposed by repo.
'''

import time
import datetime
import os
import socket
import urllib2
import urllib
import getpass
import re
import shutil
import json
from collections import defaultdict

import mercurial.commands
import mercurial.cmdutil
import mercurial.merge
import mercurial.match
import mercurial.util
import mercurial.hg
import mercurial.node
import mercurial.encoding
import mercurial.url
import mercurial.changegroup
import mercurial.discovery
from mercurial.i18n import _
from mercurial.node import nullid, short

from tortoisehg.util.version import version as thgversion

from repoman import util
from repoman import cmdutil
from repoman import forest as _forest
from repoman import extensions
import repoman.help

fromlocal = mercurial.encoding.fromlocal
tolocal = mercurial.encoding.tolocal

findcommonin = mercurial.discovery.findcommonincoming
findcommonout = mercurial.discovery.findcommonoutgoing

def status(ui, f, modified=False, added=False, removed=False, deleted=False, unknown=False, **opts):
    """show status of each module

    Displays the status of each module, showing commitable changes. If no
    options are given, modified, added, removed, deleted and unknown files are
    shown. If no modules are given, all modules are processed."""

    mask = (modified, added, removed, deleted, unknown)
    if not any(mask):
        mask = (True, True, True, True, True)

    for mod in util.sortmodules(f):
        stat = f[mod].status(unknown = mask[4])
        st = [mask[i] and stat[i] or [] for i in range(0, 5)]
        if not any(st):
            continue
        ui.write_module('\n%s\n' % mod)
        for fname in st[0]:
            ui.write('  M %s\n' % (fname,), label='status.modified')
        for fname in st[1]:
            ui.write('  A %s\n' % (fname,), label='status.added')
        for fname in st[2]:
            ui.write('  R %s\n' % (fname,), label='status.removed')
        for fname in st[3]:
            ui.write('  ! %s\n' % (fname,), label='status.deleted')
        for fname in st[4]:
            ui.write('  ? %s\n' % (fname,), label='status.unknown')
    ui.write('\n')


def commit(ui, f, message=False, date=None):
    '''commit changes in each module

    Commit changes in each module using the hgtk commit tool. If --message is
    given, you will be prompted for a common commit message and the commit is
    performed directly, bypassing hgtk commit. In that case you will not be
    able to select or deselect files, and all committable files are included.'''

    ui.status('Checking for changes... ')
    extra = []
    mergetext = ['']
    changes = []
    mergecommit = f.state and f.state.name == 'merge'

    undo = []
    if mergecommit:
        if util.commit(f.gmd_repo, 'Fast-forward of branch %s' % f.branch, [f.branch_relpath(f.branch)], date=date):
            undo.append(f.GMD)
            for hg_undo, repo_undo in f.get_gmd_undo_files():
                mercurial.util.rename(hg_undo, repo_undo)
        message = True
        mergetext = ['Merge %s to %s' % tuple(f.state.data)]

    for mod in f:
        ctx = f[mod][None]
        modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
        if modified or added or removed or len(ctx.parents()) > 1:
            if not changes:
                extra.append('HG: --')
            changes.append(mod)
            extra.append('HG: module: %s (branch %s)' %
                         (mod, ctx.branch() or 'default'))
            extra.extend([_("HG:     added %s") % file for file in added])
            extra.extend([_("HG:     changed %s") % file for file in modified])
            extra.extend([_("HG:     removed %s") % file for file in removed])

    if not changes:
        if mergecommit and undo:
            ui.status(_('fast-forward merge committed\n'))
            f.delete_state()
        elif mergecommit:
            # merge with only local fast-forward
            ui.status(_('fast-forward merge\n'))
            f.delete_state()
        else:
            ui.status(_('nothing changed\n'))
        return
    ui.status('\n')

    if message:
        text = cmdutil.get_commit_message(f, text=mergetext, extra=extra)
    for mod in changes:
        repo = f[mod]
        if message:
            if util.commit(repo, text, date=date):
                undo.append(mod)
        else:
            mercurial.util.system('hgtk commit', cwd=repo.root,
                                  onerr=util.Abort, errprefix='commit failed')
    if undo:
        f.write_undo('commit', 'Commit%s' % (' merge' if mergecommit else ''), undo)
    if message:
        ui.status('commit complete\n')
        if f.state and f.state.name == 'merge':
            f.delete_state()
    else:
        ui.status('commit tool launched\n')


def info(ui, f):
    """show information about repository

    Displays information about the current repository and checks module branch status."""

    # General information
    ui.status('%s in directory %s\n' % (
        f.solution and ('Solution %s' % ui.emph_str(f.solution))
                    or 'Repository forest',
                    ui.emph_str(util.normpath(ui, f.path))))
    if f.virtual:
        ui.status('Virtual clone from %s\n' % ui.emph_str(f.virtual))
    ui.status('Working branch: %s\n' % ui.emph_str(f.branch))
    if f.branches:
        branches, all = cmdutil.parse_branches(f.branches, current=f.branch)
        if all:
            branches = ['all branches']
        ui.status('Active branches: %s\n' % ', '.join([ui.emph_str(br) for br in branches]))
    ui.status('Modules: %s\n' % util.wrap(', '.join(f.modules), 80, 9))
    if f.state:
        ui.warn('Operation in progress: %s\n' % f.state.name)

    # Module checks
    diskmods = [m for m in f]
    if diskmods != f.modules:
        ui.warn('The following modules are in the module list but not in the directory:\n')
        ui.status(''.join(['  %s\n' % m for m in f.modules if m not in diskmods]))

    # Solution checks
    if f.solution:
        solmod, solname = f.get_solution_modules(f.solution)
        if not solmod:
            ui.warn('Solution was deleted from metadata.\n')
        else:
            missing = [m for m in solmod if m not in f.modules]
            exessive = [m for m in f.modules if m not in solmod]
            if missing:
                ui.warn('The following modules are in the solution but not in the current clone:\n')
                ui.status(''.join(['  %s\n' % m for m in missing]))
            if exessive:
                ui.warn('The following modules are in the current clone but not in the solution:\n')
                ui.status(''.join(['  %s\n' % m for m in exessive]))

    # Branch information
    tips = f.branch_tips(f.branch)
    branches = dict((mod, f[mod].dirstate.branch()) for mod in f)
    diff = [(mod, branches[mod]) for mod in f if branches[mod] != f.branch]
    if len(diff):
        ui.warn('Some modules are on different branches from the current working branch:\n')
        ui.status(''.join(['  %s (%s)\n' % x for x in diff]))
    par = [(mod, f[mod].dirstate.parents()[0]) for mod in f]
    diff = [(mod, p) for mod, p in par if mod in tips and branches[mod] == f.branch and p != tips[mod]]
    if len(diff):
        ui.warn('Some modules are not at the current branch tip:\n')
        ui.status(''.join(['  %s (%s)\n' % (mod, short(node)) for mod, node in diff]))


def parents(ui, f, style=None, template=None):
    """show parent changeset(s)

    Displays the parent changeset(s) of the working directory in each module."""

    # TODO: Burde vi ikke lave en separat style og bruge den i stedet
    # for template?
    if not template and not style:
        template = 'rev {rev} ({node|short}) committed {date|age} by {author|person}\n  summary: {desc|firstline|fill68|tabindent}\n'
    for mod in f:
        ui.write_module_header(mod)
        modrepo = f[mod]
        mercurial.commands.parents(ui, modrepo, style=style, template=template)
        ui.write('\n')


def heads(ui, f, all=False, template=None):
    '''show current module heads

    Displays the heads of each module. If no options are given, only the
    heads on the current branch of each module are shown.'''

    for mod in f:
        ui.write_module_header(mod)
        modrepo = f[mod]

        if all:
            # mercurial.commands.heads does not show terribly useful
            # information for all branches, instead we show heads
            # from the branchmap directly
            displayer = mercurial.cmdutil.show_changeset(ui, modrepo, {'template':template})
            for bn, bheads in modrepo.branchmap().iteritems():
                for n in bheads:
                    displayer.show(modrepo[n])
        else:
            mercurial.commands.heads(ui, modrepo, '.', template=template)


def serve(ui, f, port=8000, allow_push=False):
    '''serves the repository via HTTP on the specified port

    While the server is active, everyone with access may pull from your
    repository; push is not allowed.

    Use ctrl + c to stop the server.
    '''
    config = f.ljoin('hgweb.config')

    for mod in f.get_all_modules():
        rc = os.path.join(f.path, mod, '.hg', 'hgrc')
        data = None
        if os.path.exists(rc):
            with open(rc, 'r') as fl:
                data = fl.read()

        if not os.path.exists(rc) or '[web]' not in data:
            with open(rc, 'a') as fl:
                fl.write('\n[web]\nstyle = gitweb\n')

    with open(config, 'wb') as fl:
        fl.write('[web]\nstyle = gitweb\n%s[paths]\n' %
                ('push_ssl=False\nallow_push=*\n' if allow_push else ''))
        for mod in f.get_all_modules():
            fl.write('%(mod)s = %(mod)s\n' % {'mod': mod})

    ui.status('Publishing %s to http://%s:%d/\n' % (f.path, socket.gethostname(), port))
    opts = util.get_mercurial_default_opts('serve')
    opts['port'] = port
    opts['webdir_conf'] = config

    cwd = os.getcwd()
    try:
        os.chdir(f.path)
        mercurial.commands.serve(ui, f.lmd_repo, **opts)
    finally:
        os.chdir(cwd)


def outgoing_commands(ui, f, operation, dest, branches, current, force, yes,
                      style=None, template=None, bfile=None, strip=False,
                      bundleall=False, metadatapull=True):

    # Prepare.
    if branches and current:
        raise util.Abort('--branch and --current can\'t be given at the same time')
    branches, all = cmdutil.parse_branches(branches, current=f.branch, default=f.branches)
    branchmaps = f.read_branches(branches)
    push = operation == 'push'
    bundle = operation == 'bundle'
    outgoing = operation == 'outgoing'
    modules = [f.GMD] + util.sortmodules(f)
    if bundleall:
        modules.append(f.LMD)
    if bundle:
        if not os.path.splitext(bfile)[1]:
            bfile += '.repo'
        if strip:
            strip_bases = {}

    # Process a module.
    def process_module(module, outgoing, modtxt, branchplural, heads, multi):
        md = module == f.GMD or module == f.LMD
        if md:
            modname = '(metadata)' if outgoing else '(metadata out)'
        else:
            modname = module
        if outgoing:
            ui.write_module_header(modname)
        else:
            ui.write(modtxt % modname)
        if multi:
            ui.warn('multiple heads on the following branches: %s\n' % ', '.join(sorted(multi)))
            if push and not outgoing:
                return
        repo = f[module]
        if not force and hasattr(repo, 'mq') and repo.mq.applied:
            warn = False
            if not branches:
                warn = True
            else:
                qtip = repo.mq.applied[-1].node
                if any(n == qtip for n in heads):
                    warn = True
            if warn:
                ui.warn('mq patches applied')
                if push and not outgoing:
                    ui.warn('; skipped\n')
                    return
                ui.warn('\n')

        repo.ui.filter = ui.filter
        remote_ui = mercurial.hg.remoteui(repo, {})
        if bundleall:
            source_repo = None
        else:
            source_repo = mercurial.hg.repository(remote_ui, f.getsource(module, dest))

        if outgoing or bundle:
            with cmdutil.quietui(repo.ui):
                if bundleall:
                    common = [nullid]
                    csets = [repo[ctx].node() for ctx in repo]
                else:
                    commoninc = findcommonin(repo, source_repo, force=force)
                    outg = findcommonout(repo, source_repo, commoninc=commoninc,
                                                     force=force, onlyheads=heads)
                    common, csets = outg.commonheads, outg.missing
                    if not csets:
                        outg = findcommonout(repo, source_repo, commoninc=commoninc, force=force)
                        common, csets = outg.commonheads, outg.missing
                        if csets:
                            ui.status('no changes found on selected branch%s\n' % branchplural)
                            if outgoing:
                                ui.write('\n')
                            return False
            if not csets:
                ui.status('no changes found\n')
                if outgoing:
                    ui.write('\n')
                return False
            if outgoing:
                displayer = mercurial.cmdutil.show_changeset(ui, repo, {'template': template, 'style': style})
                for n in csets:
                    displayer.show(repo[n])
            elif bundle:
                cg = repo.getbundle('bundle', common=common, heads=heads)
                mercurial.changegroup.writebundle(cg, repo.join('outgoing.hg'), 'HG10BZ')
                if strip:
                    strip_bases[module] = cmdutil.find_strip_bases(repo, csets)
            return True
        elif push:
            try:
                rv = repo.push(source_repo, force=force, revs=heads, newbranch=True)
                if md and rv == 0:
                    ui.warn(modtxt % ('',))
                    ui.warn('(use "repo pull" to solve conflict and push again)\n')
            except:
                if md:
                    ui.warn('error pushing metadata; please correct and push again\n')
                raise

    # Process all modules.
    def process(outgoing):
        mods = []
        if bundleall:
            source = None
        else:
            source = f.getsource(source=dest)
        branchplural = 'es' if branches and len(branches) > 1 else ''
        branchtxt = ('current head' if current else
                     'all branches' if not branches else
                     'branch%s: %s' % (branchplural, ', '.join(branches)))

        # Prepare.
        if outgoing:
            ui.write_header('Outgoing changes to %s (%s)\n\n' % (util.normpath(ui, source), branchtxt))
            modtxt = None
        elif push or bundle:
            if push:
                ui.write_header('Pushing to %s (%s)\n' % (util.normpath(ui, source), branchtxt))
            else:
                ui.write_header('Bundling changes to %s (%s)\n' % (util.normpath(ui, source), branchtxt))
            modtxt = cmdutil.modstr_tmpl(ui, modules, metadata=True, inout=True)
            ui.filter = re.compile('^(comparing with |searching for changes$|remote: |adding |' +
                                   'note: unsynced |\\(did you forget to merge\\? use push -f to force)')

        # Pull metadata, read branch heads and check for multiple heads.
        if not outgoing and not bundleall and metadatapull:
            ui.write(modtxt % '(metadata in)')
            cmdutil.pull_metadata(f, source=dest, terse=True)
            f.gmd_repo.invalidate()
        headmaps = cmdutil.get_headmaps(f, modules, current, branches)
        multi = {}
        aborting = False
        modules2 = modules
        if branches:
            for mod in modules:
                bmap = headmaps[mod]
                mult = [b for b in bmap if len(bmap[b]) > 1]
                if mult:
                    multi[mod] = mult
            if multi and push:
                aborting = True
                if not outgoing:
                    modules2 = multi.keys()

        # Perform outgoing/push operation.
        for mod in modules2:
            if branches and mod != f.GMD:
                heads = [hd for hds in headmaps[mod].itervalues() for hd in hds]
            else:
                heads = None
            if process_module(mod, outgoing, modtxt, branchplural, heads, multi.get(mod)):
                mods.append(mod)
        if push:
            ui.filter = None
        if aborting:
            raise util.Abort('push aborted due to multiple heads')
        return mods

    # Preview (or display outgoing).
    if outgoing or not yes:
        modules = process(outgoing=True)
        if modules and not outgoing:
            answer = ui.prompt('%s these changes (y/yes/n/no)?' % operation.title(), 'n')
            if answer not in ['y', 'yes']:
                ui.status('%s aborted.\n' % operation.title())
                return

    # Push or bundle.
    if not outgoing:
        if modules:
            modules = process(outgoing=False)
            if modules and bundle:
                ui.status('Writing bundle file %s\n' % bfile)
                bf = _forest.Bundle(bfile, 'w')
                for mod in modules:
                    src = f[mod].join('outgoing.hg')
                    bf.add(mod, src)
                    try:
                        os.unlink(src)
                    except Exception:
                        pass
                bf.close()
                if strip:
                    ui.status('Stripping bundled changesets..')
                    f.clear_undo()
                    for mod, bases in strip_bases.iteritems():
                        cmdutil.strip(ui, f[mod], *[f[mod][b].hex() for b in bases])
                        ui.write('.')
                    ui.status(' done\n')
            if push:
                f.clear_undo()
        else:
            ui.status('Nothing to %s.\n' % operation)

def outgoing(ui, f, dest=None, **opts):
    """show outgoing changes without pushing them

    Displays outgoing changes to a source, without actually pushing them.
    If no source is given, the original clone source is assumed. If no modules
    are given, all modules are processed. If no branches are given, changes are
    displayed for the current working branch only. If --current is given, only
    the current repository heads are considered for pushing. Otherwise, if
    there are multiple heads on any selected branch, a warning is displayed."""

    outgoing_commands(ui, f, 'outgoing', dest, opts['branch'],
                      opts['current'], opts['force'], yes=False,
                      style=opts['style'], template=opts['template'])

def push(ui, f, dest=None, **opts):
    '''pushes local changes

    If no source is given, the original clone source is assumed. If no modules
    are given, all modules are processed. If no branches are given, changes are
    pushed from the current working branch only. Otherwise, if there are
    multiple heads on any branch to be pushed, an error is reported. Before
    actually pushing, a review of outgoing changes is provided unless the
    --noninteractive option is used.

    During the push, each module can trigger an error being reported, in
    particular that the push creates new remote heads. If the error reports
    that new heads would be created, then you must solve that by first pulling
    the latest changes and either rebasing your changes or merging them using
    "repo rebase" or "hg merge" in each module that reported the error.
    '''

    outgoing_commands(ui, f, 'push', dest, opts['branch'],
                      opts['current'], opts['force'],
                      yes=opts['noninteractive'],
                      style=opts['style'],
                      template=opts['template'],
                      metadatapull=not opts['no_metadata_pull'])

def bundle(ui, f, fname, dest=None, **opts):
    '''create a bundle

    The bundle contains changes for all modules that have outgoing changes on
    the selected branches.
    '''

    outgoing_commands(ui, f, 'bundle', dest,
                      opts['branch'] if not opts['all'] else ['*'],
                      opts['current'], opts['force'], yes=opts['noninteractive'],
                      bfile=fname, strip=opts['strip'], bundleall=opts['all'])


def ingoing_commands(ui, f, operation, source = 'default', branch=None,
                     current=False, noupdate=False, style=None, template=None,
                     log=False, modmap=None, clean=None):
    '''Common code for incoming, pull and unbundle.'''

    # Prepare.
    if operation == 'incoming':
        incoming = True
        header = 'Incoming'
    elif operation == 'pull':
        incoming = False
        header = 'Pulling'
    else:
        raise util.Abort('internal error; unknown ingoing_commands operation %s' % operation)

    usebundle = os.path.isfile(source)
    if current:
        if modmap:
            raise util.Abort('--modmap and --current can\'t be given at the same time')
        if branch:
            raise util.Abort('--branch and --current can\'t be given at the same time')
        branches, all = None, False
    else:
        default = ['*'] if usebundle else f.branches
        branches, all = cmdutil.parse_branches(branch, current=f.branch, default=default)

    modules = list(f)
    if usebundle:
        bundle = _forest.Bundle(source)
        bundlemd = f.GMD in bundle.modules
        modules = [mod for mod in modules if mod in bundle.modules]
    else:
        bundle = None

    modmap = dict((k.strip(), v.strip()) for k, v in (e.split('=', 1) for e in modmap))
    for mod in modmap:
        if mod not in modules:
            raise util.Abort('invalid --modmap: module %s not in forest' % mod)

    quiet = ui.quiet
    sourctxt = source if bundle else f.getsource(source=source)
    if all:
        branchestxt = 'all branches'
    elif current:
        branchestxt = 'current branch'
    else:
        branchestxt = 'branches: %s' % ", ".join(branches)
    ui.write_header('%s changes from %s (%s)\n' % (header, util.normpath(ui, sourctxt), branchestxt))
    if bundle:
        local_modules = f.get_all_modules(with_metadata=True, with_local=False)
        missing_locally = [mod for mod in bundle.modules if mod not in local_modules]
        if missing_locally:
            modulesplural, verb = ('modules','are') if len(missing_locally) > 1 else ('module','is')
            ui.warn('The %s %s in the bundle %s not part of the (local) forest\n' % 
                (modulesplural, ", ".join(missing_locally), verb))
    if not quiet and not(log and bundle): ui.write('\n')

    opts = {}
    opts['style'] = style
    opts['template'] = template
    opts['rev'] = opts['force'] = None
    opts['bundle'] = f.gjoin('.bundle') if incoming and branches else None
    opts['update'] = not incoming
    opts['rebase'] = False

    if quiet or log:
        modstr = cmdutil.modstr_tmpl(ui, modules, metadata=True)

    def header(text):
        if quiet:
            ui.write(modstr % text)
        else:
            ui.write_module_header(text)

    # Write output in quiet mode
    def quiet_write():
        num_csets = len(ui.buffer)
        del ui.buffer[:]
        ui.buffered = False
        ui.write('%d new changesets\n' % num_csets)

    # Write warning if a bundle error occurs
    def bundle_error(error):
        ui.warn('bundle error: changeset %s is missing locally\n' % short(error.name))

    # Process metadata.
    undo = []
    ui.filter = re.compile('^(pulling from |comparing with |searching for changes$|adding |\\(run \'hg |not updating)')
    if branches:
        oldmaps = dict((b, f.read_branch(b)) for b in branches)
    repo = f.gmd_repo
    if bundle:
        if bundlemd:
            bfile = repo.join('unbundle.hg')
            bundle.get(f.GMD, bfile)
            src = 'bundle:%s+%s' % (repo.root, bfile)
        else:
            src = None
    else:
        src = f.getsource(f.GMD, source)

    anymeta = False
    if src:
        header('(metadata)')
        try:
            if incoming:
                if quiet:
                    opts['template'] = '.'
                    ui.buffered = True
                anymeta = mercurial.commands.incoming(ui, repo, src, **opts) == 0
                if quiet:
                    quiet_write()
            else:
                prevlen = len(repo)
                cmdutil.pull(ui, repo, src, **opts) 
                if len(repo) > prevlen:
                    anymeta = prevlen
                    undo.append(f.GMD)
                    for hg_undo, repo_undo in f.get_gmd_undo_files():
                        mercurial.util.copyfile(hg_undo, repo_undo)

                    heads = [x for x in repo.heads() if repo[x].rev() != repo['.'].rev()]
                    while len(heads) >= 1:
                        if mercurial.hg.merge(repo, heads[0], remind=False):
                            ui.prompt('resolve conflicts then press enter...')
                        util.docmd_encoding(lambda: repo.commit('merge'))
                        heads = [x for x in repo.heads() if repo[x].rev() != repo['.'].rev()]

                # no need to explicitly update metadata, already done by the rebase after pull
        except util.LookupError, e:
            if not bundle:
                raise
            bundle_error(e)

        if not incoming or not anymeta:
            ui.status('\n')

    opts['bundle'] = opts['update'] = opts['rebase'] = None
    if incoming and log and not quiet:
        quiet = True
        opts['template'] = '.'

    # Collect new branch maps (after metadata changes).
    if branches:
        skippedbranches = []
        def skipwarn(b):
            ui.warn('skipping unknown branch %s\n' % b)
            skippedbranches.append(b)
        newmaps = {}
        if not anymeta or not incoming:
            for branch in branches:
                newmaps[branch] = bmap = f.read_branch(branch)
                if not bmap:
                    skipwarn(branch)
        else:
            brepo = f.bundle_repo(f.GMD, '.bundle')
            tipctx = brepo['tip']
            for branch in branches:
                bpath = f.branch_relpath(branch)
                if bpath not in tipctx:
                    skipwarn(branch)
                    continue
                bdata = tipctx[bpath].data().split('\r\n')
                newmaps[branch] = util.parse_branch(branch, bdata, oldmaps[branch].l)
        branches = [b for b in branches if b not in skippedbranches]
        if not branches:
            ui.warn('no valid branches given. aborting.\n')
            return

        # Augment branches for module-mapped pulls.
        if modmap:
            for b in branches:
                for d, s in modmap.iteritems():
                    bdata = newmaps[b]
                    if s in bdata and d not in bdata.g:
                        bdata.l[d] = bdata[s]

        branchupdate = newmaps.get(f.branch)
    elif all:
        branchupdate = f.read_branch(f.branch)

    # Process regular modules.
    ui.filter = re.compile('^(pulling from |comparing with |searching for changes$|adding |\\(run \'hg )')
    anymods = {}
    view_log = []
    bundleerror = False
    for mod in modules:
        srcmod = modmap and modmap.get(mod) or mod
        if srcmod != mod:
            header('%s (from %s)' % (mod, srcmod))
        else:
            header(mod)
        skip_ingoing = False
        repo = f[mod]
        if bundle:
            bfile = repo.join('unbundle.hg')
            bundle.get(mod, bfile)
            src = 'bundle:%s+%s' % (repo.root, bfile)
        else:
            src = f.getsource(srcmod, source)
        try:
            if branches:
                remote = mercurial.hg.repository(ui, src)
                opts['other'] = remote
                revs = []
                bnames = []
                for branch in branches:
                    newbr = newmaps[branch]
                    if not mod in newbr:
                        continue
                    oldbr = oldmaps[branch]
                    if mod in oldbr and oldbr[mod] != newbr[mod]:
                        ui.status('Branch %s was fast-forwarded to %s\n' % (branch, newbr[mod][:12]))
                    if util.rev_exists(remote, branch):
                        bnames.append(branch)
                    node = newbr[mod]
                    if not util.rev_exists(f[mod], node):
                        revs.append(node)

                if not revs and not bnames:
                    skip_ingoing = True
                if skip_ingoing:
                    if quiet:
                        ui.write('0 new changesets\n')
                    else:
                        ui.status('no changes found\n')

            elif all: # all branches
                bnames = []
                revs = []

            else: # dirstate branch
                opts['other'] = None
                revs = None
                bnames = [f[mod].dirstate.branch()]

            if not skip_ingoing:
                opts['rev'] = revs
                opts['branch'] = bnames
                if incoming:
                    if quiet:
                        if log:
                            opts['bundle'] = os.path.join(f[mod].path, 'incoming.hg')
                        ui.buffered = True
                    skip_ingoing = mercurial.commands.incoming(ui, f[mod], src, **opts) != 0
                    if quiet:
                        if log and not skip_ingoing:
                            view_log.append(mod)
                        quiet_write()
                else:
                    lastrev = len(f[mod])
                    skip_ingoing = cmdutil.pull(ui, f[mod], src, **opts) == 0
                    if not skip_ingoing:
                        undo.append(mod)
                        anymods[mod] = lastrev

            if not incoming:
                nodes = (not current) and branchupdate and f.module_branch_heads(f.branch, mod, branchupdate) or None
                if nodes or current:
                    wctx = repo[None]
                    rev = current and repo.branchtags()[wctx.branch()] or nodes[0]
                    if len(wctx.parents()) > 1 or wctx.p1() != repo[rev]:
                        if noupdate:
                            ui.status('note: module is not at branch head\n')
                        else:
                            if quiet:
                                ui.write(modstr % '')
                            p1 = repo['.']
                            p2 = repo[rev]
                            pa = p1.ancestor(p2)
                            if not clean and pa != p1 and pa != p2 and p1.branch() == p2.branch():
                                ui.warn('warning: update crosses branches (use "repo rebase" or "hg merge")\n')
                            else:
                                if clean:
                                    cmdutil.backup_changes(repo, rev)
                                    mercurial.hg.clean(repo, rev)
                                else:
                                    mercurial.hg.update(repo, rev)
                                repo.dirstate.setbranch(f.branch)

        except util.LookupError, e:
            ui.buffered = False
            if not bundle:
                raise
            bundle_error(e)
            bundleerror = True
            skip_ingoing = True

        finally:
            if not quiet and (skip_ingoing or not incoming):
                ui.write('\n')
            remote = opts.get('other')
            if remote and hasattr(remote, 'close'):
                remote.close()

    # Update individual modules' .hg/hgrc files
    if not incoming and anymeta:
        cmdutil.update_configurations(ui, f)

    # Post-pull hook.
    anyrealmods = len(anymods)
    if not incoming:
        if anymeta is not False:
            anymods[f.GMD] = anymeta
        if not branches:
            newmaps = {}
        cmdutil.post_pull_hook(ui, f, anymods, newmaps, modmap)

    # Update local branches for module-mapped pulls.
    if modmap and branches and anyrealmods:
        for b in newmaps:
            f.write_branch(b, newmaps[b], oldmaps.get(b), local=True)

    ui.filter = None
    if bundle:
        bundle.close()
    if undo:
        f.write_undo('pull', 'Pull from %s, %s' % (util.normpath(ui, sourctxt), branchestxt), undo)
    if not bundleerror and view_log:
        for mod in view_log:
            mercurial.util.system('hgtk --fork -R bundle:.hg/incoming.hg log', cwd=f[mod].root,
                    onerr=util.Abort, errprefix='log failed')
        time.sleep(1)


def incoming(ui, f, *args, **opts):
    '''show incoming changes without pulling them in

    Displays incoming changes from a source without actually pulling them in.
    If no source is given, the original clone source is assumed. If no branches
    are given, changes are displayed for the current working branch only.'''

    ingoing_commands(ui, f, 'incoming', *args, **opts)

def pull(ui, forest, *args, **opts):
    '''pulls in changes from source

    If no source is given, the original clone source is assumed. If no branches
    are given, changes are pulled in on the current working branch only.

    After pulling the current branch, an update will be performed similar to
    issuing the command "repo update --merge". The --clean option can be used
    to turn this into "repo update --clean" instead. Finally, the --noupdate
    option can be used to skip the update.
    '''

    ingoing_commands(ui, forest, 'pull', *args, **opts)


def update(ui, f, node=None, branch=None, **opts):
    '''update the repository forest to the given branch name

    The command recursively updates each module in the forest.
    Status information is displayed along the way. If you update to a new
    branch, this will be set as your current working branch (see repo info).

    repo update can also be used to switch to local revision names (e.g.
    bookmarks), if the --local option is given.

    If --clean is specified, update will create a backup .orig file for each
    file that has been modified, unless --nobackup is specified. To restore the
    .orig files to modified files see 'repo help unrevert'.

    If the --date option is given, the method tries to suggest changesets on
    the selected branch that matches this date specification. It is impossible
    to do this perfectly as rebases reorder the chronology of changesets. For
    each module, a list of possible changesets that matches the specified date
    range is suggested.

    Each of the date specifications will only be applied to changesets on the
    specified branch and their ancestors. If no branch is specified, the
    forest's current branch will be used.

    The delta option is only used for range and specific date specifications
    where no changesets match exactly.

    The date ranges can be specified in the following ways:

    "<date"  Find the greatest changeset less than date.
    ">date"  Find the least changeset greater than date.
    "date1 to date2"  Find changesets between date1 and date2.
    "date"  Find changeset at date.

    To see how the exact date specifications are written, see "hg help dates".
    '''

    if node:
        if branch:
            raise util.Abort('please specify just one revision')
        branch = node
    branch = cmdutil.parse_branches(branch, exact=True, current=f.branch)[0]

    clean = opts['clean']
    nobackup = opts['nobackup']
    merge = opts['merge']

    if f.state and f.state.name == 'merge' and not clean:
        raise util.Abort('merge in progress, use --clean to abort the merge')

    # todo: refactor to use common update code further down
    if opts['date']:
        if clean or merge:
            raise util.Abort('when using --date, options --clean and --merge are not currently supported')
        cmdutil.timeupdate(ui, f, opts['date'], branch=branch,
                delta=opts['delta'])
        return

    # undo merge state if there are fast-forwards
    if f.state and f.state.name == 'merge':
        mercurial.merge.update(f[_forest.Forest.GMD], None, False, clean, None)

    # Find the update target.
    rev = branch
    branch = f.read_branch(rev)
    revs = None
    if not branch:
        if rev != '.' and not opts['local']:
            raise util.Abort('unknown branch %s' % rev)
    elif opts['base']:
        revs = f.read_branch(rev, base=True)
    else:
        revs = f.branch_tips(rev, branchmap = branch)

    # Check if update is needed.
    wdir = {}
    target = {}
    needed = set()

    modules = list(f)
    for mod in f:
        here = f[mod][None]
        try:
            if revs and mod not in revs:
                ui.warn('module "%s" isn\'t covered by the specified branch.\n' % mod)
                modules.remove(mod)
                continue

            r = revs and revs[mod] or rev
            there = f[mod][r]
        except util.RepoError:
            raise util.Abort('unknown revision %s in %s' % (r, mod))
        wdir[mod] = here
        target[mod] = there
        if len(here.parents()) > 1 or here.p1() != there:
            needed.add(mod)

    # Check for modified files.
    if needed and not clean and not merge:
        for mod in needed:
            if wdir[mod].files() or wdir[mod].deleted():
                raise util.Abort('changed files in %s' % mod)

    # Check if we can perform the update.
    if needed and not clean and not opts['partial']:
        error = None
        for mod in needed:
            wc = wdir[mod]
            if len(wc.parents()) > 1:
                raise util.Abort('outstanding uncommitted merge in %s; use --clean to discard changes' % mod)
            here = wc.p1()
            there = target[mod]
            anc = here.ancestor(there)
            if anc == here or anc == there:
                pass
            elif here.branch() == there.branch():
                error = 'update crosses branches in %s; use --clean to allow' % mod
            elif wc.files() or wc.deleted():
                raise util.Abort('changed files and update crosses branches in %s; use --clean to discard changes' % mod)
        if error:
            raise util.Abort(error)

    # Update to target, backing up as needed.
    if modules:
        modtxt = cmdutil.modstr_tmpl(ui, modules)
        ui.write_header('Updating to %s:\n' % rev)

        for mod in modules:
            ui.status(modtxt % mod)
            repo = f[mod]

            if not clean and mod not in needed:
                ui.status('No update needed\n')
            else:
                if clean and not nobackup and util.rev_exists(repo, rev):
                    cmdutil.backup_changes(repo, rev)
                stats = mercurial.merge.update(repo, target[mod].node(), False, clean, None)
                mercurial.hg._showstats(repo, stats)
            if revs:
                repo.dirstate.setbranch(rev)
    else:
        ui.status('Empty forest; current branch switched to %s\n' % ui.emph_str(rev))

    if f.state and f.state.name == 'merge':
        f.delete_state()

    if revs: f.branch = rev

def metadata(ui, f, **opts):
    '''show repository metadata

    Displays metadata, as contained in a solution or module collection.

    To list available solutions specify -s/--solutions.

    To list available branches matching a pattern specify -b/--branches
    followed by the pattern. The pattern may include '*' to match a single
    namespace component and '**' to match a number of components. For
    example '*/dev' matches all two-component branches ending in 'dev' (for
    example 'core/dev' and 'customer/dev', but not 'customer/topic/dev'),
    while '**/dev' matches all branches ending with '/dev' (for example
    'core/dev', 'customer/dev', and 'customer/topic/mytopic/dev').'''

    if opts['solutions'] and opts['branches']:
        raise util.Abort('please specify either --solutions or --branches, not both\n')
    if not opts['solutions'] and not opts['branches']:
        raise util.Abort('please specify one of --solutions or --branches')

    def sol(solution):
        return f.gjoin('solutions', solution)
    def modules(fname):
        if not opts['show_modules']:
            return ''
        return ' (%s)' % ', '.join(
            [l.decode('utf-8-sig').strip().split(' ')[-1] for l in file(fname) ])

    if opts['solutions']:
        ui.write('Solutions:\n')
        ui.write('\n'.join(
            util.sort(
           [ '  %s%s' % (s, modules(sol(s))) for s in os.listdir(sol('')) if os.path.isfile(sol(s))])))
        ui.write('\n')
    else:
        branches = opts['branches']
        ui.write("Branches matching '%s'\n" % branches)
        # translate branch pattern to a regular expression
        branchpat = re.compile(branches.replace('\\','/').replace('**','.#').replace('*','[^/]*').replace('#','*').replace('?','[^/]?') + "$")
        branchesroots = [f.branches_gmd_path, f.branches_lmd_path]
        def walker(branchesroot, dirname, fnames):
            parent = dirname[len(branchesroot)+1:]
            for fn in fnames:
                if fn == '.keep':
                    continue
                file = os.path.join(dirname, fn)
                branch = os.path.join(parent, fn).replace('\\','/')[:-2]
                if os.path.isfile(file) and  branchpat.match(branch):
                    branchinfo = f.read_branch(branch)
                    if branchinfo:
                        if branchesroot == branchesroots[-1] and list(branchinfo.iterkeysglobal()):
                            continue
                        ui.write("  %s%s\n" % (branchinfo.name, '' if not opts['show_modules'] else (' (%s)' % (', '.join(sorted(list(branchinfo))),))))
                        if opts.get('date'):
                            binfo = f.branch_info(branch)
                            if binfo:
                                valid = ['Created branch', 'Extended branch', 'Moved branch']
                                for binf in binfo:
                                    bctx = f.gmd_repo[binf[0]]
                                    desc = bctx.description().splitlines()[0]
                                    if not any(map(lambda x: desc.startswith(x), valid)):
                                        continue

                                    ui.write('    %s: %s\n' % (
                                        mercurial.util.datestr(bctx.date(), '%Y-%m-%d'),
                                        desc))

        for branchesroot in branchesroots:
            os.path.walk(branchesroot, walker, branchesroot)


def paths(ui, f, add=[], remove=[], **opts):
    '''manage list of path aliases

    Displays and manages the path alias list, which is a list of aliases
    to commonly used remote repositories. These can be used with repo
    incoming, outgoing, pull and push. Aliases can be added (or replaced)
    and removed using the respective options. If no options are given, the
    current path list is displayed.

    Some alias names are used for special purposes:

        default        The default remote repository if none is given.
        default-push   The default remote reposityry for outgoing and push.
                       If not given, default is used instead.
        clone          Initially set to the repository cloned from, but
                       otherwise unused. This will normally be identical
                       to default unless --detach was used when the forest
                       was cloned.'''

    add = dict([x.strip() for x in a.split('=', 1)] for a in add)
    if set(add) & set(remove):
        raise util.Abort('only one of -a/--add and -r/--remove may be given for the same name: %s.\n'
            % ', '.join(set(add) & set(remove)))

    sourcemap = f.read_source_map()
    for rem in remove:
        if rem in sourcemap:
            del sourcemap[rem]
        else:
            ui.warn('unknown alias %s, skipping\n' % rem)
    sourcemap.update(add)
    if add or remove:
        f.write_source_map(sourcemap)
        util.commit(f.lmd_repo, 'updated paths')

    ui.write('Current path aliases:\n')
    ui.write(''.join(['  %s = %s\n' % (name, util.normpath(ui, sourcemap[name])) for name in sorted(sourcemap.iterkeys())]))


def clone(ui, source, sln=None, branch=[], noupdate=False, solution=None, dest=None,
          empty=False, detach=False, module=[], **opts):
    '''clone a solution or module collection

    If a solution name is given, all solution modules are cloned. If --module or --empty are given, a module collection is cloned with the given modules or no modules respectively; the latter is useful for master clones (see also repo vclone). If neither --solution, --module or --empty are given, a module collection with all available modules is cloned.

    If no branches are given, all available branches are included, and --noupdate is implied.

    The new clone will by default push and pull against the source. If --detach is given, it will instead push and pull against the same repository as the source.
    '''
    # credentials check
    if not ui.config('ui','username'):
        raise util.Abort('no username specified in mercurial.ini\n\nPlease run "hgtk userconfig" and specify "Username" in the "Commit" tab. \nThe username should be on the form NAME <EMAIL>, e.g. John Doe <john.doe@email.com>.')

    # Sanity checks.
    if not branch:
        raise util.Abort('at least one branch must be specified')
    if sln and solution:
        raise util.Abort('please specify just one solution')
    if not solution:
        solution = sln
    if not dest:
        dest = solution or source[max(source.rfind('/'), source.rfind('\\'))+1:]
        if not dest:
            raise util.Abort('you must specify a destination')
    if not util.is_local(dest):
        raise util.Abort('you must specify a local destination')
    if os.path.exists(dest):
        raise util.Abort('destination "%s" already exists' % dest)
    if len([None for x in (solution, module, empty) if x]) != 1:
        raise util.Abort('exactly one of --solution, --module, and --empty must be specified')
    if util.is_local(source):
        try:
            sf = _forest.Forest(ui, source)
        except util.Abort:
            raise util.Abort('source is not a repository forest')
    if empty:
        module = []
    branch, all = cmdutil.parse_branches(branch)

    try:

        # Clone and adjust metadata.
        local_source = util.is_local(source)
        if solution:
            ui.write_header('Cloning solution %s into %s (from %s)\n' %
                            (solution, util.normpath(ui, os.path.abspath(dest)),
                             util.normpath(ui, os.path.abspath(source)) if local_source else util.normpath(ui, source)))
        else:
            ui.write_header('Cloning modules from %s into %s\n' % (util.normpath(ui, source), util.normpath(ui, dest)))
        df = cmdutil.preclone(ui, source, dest)
        if solution:
            module, solution = df.get_solution_modules(solution)
            if not module:
                raise util.Abort('solution %s is unknown' % solution)
            if df.solution and df.solution != solution:
                raise util.Abort('source is a clone of the %s solution' % df.solution)
            df.solution = solution
        elif '*' in module:
            module = list(df.modules)
        if branch:
            branch = df.read_branches(branch)
            df.branch = branch[-1][0]

        # Fetch modules and wrap up.
        ui.status('Cloning modules:\n')
        df.clone_modules(module, branch, noupdate=noupdate)
        msg = 'Clone of %s' % source
        if solution:
            msg += ' (solution %s)' % solution
        if not detach:
            df.paths['default'] = df.paths['clone']
        df.paths = df.paths
        util.commit(df.lmd_repo, msg)

        # Update configuration
        cmdutil.update_configurations(ui, df)

    except:
        shutil.rmtree(dest)
        raise


def unclone(ui, path, force=False):
    '''removes a cloned solution or module forest

    Safely removes a cloned solution or module forest, removing symbolic links,
    etc., correctly. Always use this command to delete virtual clones.'''

    if not os.path.isdir(path):
        raise util.Abort('solution or module forest not found.')
    if not force and not os.path.isdir(os.path.join(path, '.repo')):
        raise util.Abort("target doesn't appear to be a solution or module forest; use --force to remove anyway.")

    for entry in os.listdir(path):
        try:
            os.rmdir(os.path.join(path, entry))
        except (IOError, OSError):
            pass
    shutil.rmtree(path)


def branch(ui, f, name, create=False, extend=False, move=False, null=False, date=None, root=False):
    '''creates and manages branches

    Creates, extends, moves or displays information about branches.
    
    In order to extend a branch, clone the module using hg into the current
    forest and run "repo branch -e <BRANCH-NAME>".
    '''

    name = cmdutil.parse_branches(name, exact=True)[0]
    actions = [a for a in (create, extend, move) if a]
    if len(actions) > 1:
        raise util.Abort('at most one action (create, extend, move) can be given')
    branch = f.read_branch(name)

    # Branch information
    if not len(actions):
        if not branch:
            raise util.Abort('branch %s not found' % name)
        info = f.branch_base_info(name, silent=True)
        if info is not None:
            ui.status('Branch %s (created %s by %s)\n' %
                      (ui.emph_str(name),
                       mercurial.util.datestr(info.date(), format='%Y-%m-%d %H:%M:%S'),
                       util.longuser(info.user())))
            ui.status('Modules: %s\n' % util.wrap(', '.join(util.sortmodules(branch.iterkeys())), 80, 9))
        else:
            info = f.read_branch(name, base=True)
            if info:
                ui.status('Branch %s (local branch)\n' % (ui.emph_str(name)))
                ui.status('Modules: %s\n' % util.wrap(', '.join(util.sortmodules(info.iterkeys())), 80, 9))
        return

    # Read and validate dirstate
    dirstate = f.read_dirstate()
    if not null:
        for mod in dirstate:
            if dirstate[mod] == cmdutil.nullidstr:
                raise util.Abort('module %s has no working copy; maybe you forgot to update?' % mod)

    # Handle branch extend and move
    if branch:
        if create:
            raise util.Abort('branch already exists; use --extend or --move instead.')
        if extend:
            if not branch.g:
                raise util.Abort('branch is local, cannot extend (see repo help localbranch).')
            newmods = set(f) - set(branch)
            if not newmods:
                ui.status('Branch already contains all modules; nothing to do.\n')
                return
            util.dict_trim(dirstate, newmods)
            op = 'extend'
            cmsg = 'Extended branch %s'
        elif move:
            if not branch.g:
                raise util.Abort('branch is local, cannot move (see repo help localbranch).')

            util.dict_trim(dirstate, set(branch))
            active = dict(x for x in
                    [(m, [y for y in f[m].branchheads(name) if f[m][dirstate[m]].ancestor(f[m][y]) != f[m][y]])
                        for m in dirstate] if x[1]
                    )
            if active:
                ui.write_err('The following modules have unmerged heads on branch %s:\n' % name)
                modtxt = '    %s(%%d heads)\n' % cmdutil.modstr_tmpl(ui, active)
                ui.status(''.join([modtxt % (mod, len(active[mod])) for mod in util.sortmodules(active)]))
                return
            op = 'move'
            cmsg = 'Moved branch %s'

    # Handle branch creation
    else:
        if not create:
            raise util.Abort("branch doesn't exist; use --create to create it instead.")
        branchdir = f.gjoin('branches')
        root_branches = [] if not os.path.isdir(branchdir) else os.listdir(branchdir)
        branch_parts = name.split('/')
        if len(branch_parts) == 1 or branch_parts[0] not in root_branches:
            if not root:
                raise util.Abort('creating new root branches is not allowed')
        op = 'create'
        cmsg = 'Created branch %s'

    # Write branch and wrap up
    if not f.write_branch(name, dirstate, branch):
        ui.status('no changes to branch; nothing to do.\n')
        return
    if util.commit(f.gmd_repo, cmsg % name, [f.branch_relpath(name)], date=date):
        f.write_undo('branch %s' % op, cmsg % name, [f.GMD], extra=[f.branch])
    if create:
        f.branch = name
        for mod in f:
            f[mod].dirstate.setbranch(name)
    ui.write_header((cmsg % name) + ':\n')
    modtxt = cmdutil.modstr_tmpl(ui, dirstate) + '%s\n'
    ui.status(''.join([modtxt % (mod, dirstate[mod][:12]) for mod in util.sortmodules(dirstate)]))
    ui.status('Working branch: %s\n' % f.branch)

def merge(ui, f, name, dry_run=False, no_status=False, **opts):
    '''merges branches

    Merges another branch into the current one, handling each module in turn.
    If there are no changes on the current branch, a fast-forward will be
    performed instead of a merge.

    A status window will be launched for any modules with resolved files.
    Remember to review these before committing.

    To complete the merge use "repo commit". To abort the merge use
    "repo update --clean".
    '''

    # Various sanity checks.
    if name == f.branch:
        raise util.Abort('how would I merge a branch into itself?')
    name = cmdutil.parse_branches(name, exact=True)[0]
    other_branch = f.read_branch(name)
    if not other_branch:
        raise util.Abort('branch %s not found.' % name)
    local_branch = f.read_branch(f.branch)
    modules = set(f) & set(local_branch) & set(other_branch)
    util.dict_trim(local_branch, modules)
    util.dict_trim(other_branch, modules)
    try:
        other_tips = f.branch_tips(name, other_branch)
    except util.LookupError:
        raise util.Abort('branch %s not found in one or more modules; forgot to pull?' % name)
    local_tips = f.branch_tips(f.branch, local_branch)
    if any([f[mod].dirstate.parents()[0] != local_tips[mod] for mod in modules]):
        raise util.Abort('working copy is not positioned correctly on branch %s; use repo info for details.' % f.branch)

    # Check that there are no outstanding uncommited changes in any module.
    for mod in f:
        if [file for cat in f[mod].status()[:4] for file in cat]:
            raise util.Abort("one or more modules have outstanding uncommited changes (use 'repo status' to list changes)")

    # Figure out what do to.
    actions = {}
    forwards = False
    merges = False
    for mod in f:
        if mod not in modules:
            actions[mod] = 'skip; module not in both branches'
        else:
            local, other = local_tips[mod], other_tips[mod]
            anc = f[mod].changelog.ancestor(local, other)
            if anc == other:
                actions[mod] = 'skip; other is ancestor of local'
            elif anc == local == f[mod].lookup(local_branch[mod]):
                local_branch[mod] = mercurial.node.hex(other_tips[mod])
                actions[mod] = 'fast-forward'
                forwards = True
            else:
                actions[mod] = 'merge'
                merges = True

    # Perform fast-forwards if needed.
    modmaxlen = max([len(mod) for mod in f])
    ui.status('\nMerging %s into %s\n\n' % (name, f.branch), label='repoman.mergeheader')
    if not dry_run:
        if forwards:
            f.add_state('merge', [name, f.branch])
            f.write_branch(f.branch, local_branch)

    def merge_or_update(mod, merge=False):
        repo = f[mod]
        with cmdutil.quietui(repo.ui) as ignore:
            br = repo.dirstate.branch()
            stats = mercurial.merge.update(repo, other_tips[mod], merge, False, None)
            repo.dirstate.setbranch(br)
            return stats

    # Perform merges, if needed, and report actions.
    actiontxt = '%%-%ds  %%s' % modmaxlen
    failed = False
    review = []
    for mod in util.sortmodules(f):
        action = actions[mod]
        ui.status(actiontxt % (mod, action), label='repoman.mergeaction')
        if not dry_run and action == 'merge':
            if f.state is None:
                f.add_state('merge', [name, f.branch])
            stats = merge_or_update(mod, True)
            ui.status('; ')
            mercurial.hg._showstats(f[mod], stats)
            if stats[3]:
                ui.warn('  merge failed! use hg resolve -a to retry.\n')
                failed = True
            elif stats[1]:
                review.append(mod)
        else:
            if not dry_run and action == 'fast-forward':
                merge_or_update(mod)
            ui.status('\n')

    if failed:
        ui.warn('merge incomplete. fix modules with issues then use "repo commit" to complete the merge or use "repo update --clean" to undo the merge\n')
    else:
        ui.warn('merge complete - use "repo commit" to complete the merge after reviewing or "repo update --clean" to undo the merge\n')
    if review and not no_status:
        for mod in review:
            mercurial.util.system('hgtk status', cwd=f[mod].root,
                    onerr=util.Abort, errprefix='status failed')

def help(ui, command=None):
    """show help for a command

    Displays help about a repo command."""

    exts, maxlength = extensions.enabled()

    cmd_dict = dict(commands)
    for name, ext in extensions.extensions():
        cmd_dict.update(ext.cmdtable)

    aliases = cmdutil.build_alias_map(cmd_dict)
    try:
        cmd = cmdutil.findcmd(command, cmd_dict, aliases) if command else None
    except util.AmbiguousCommand, inst:
        ui.write('error: ambiguous command - possible commands: %s\n' %
                ', '.join([cmd[0] for cmd in inst.args[1]]))
        return
    except util.UnknownCommand, inst:
        if command not in exts and command not in repoman.help.topics:
            ui.write('error: unknown command "%s"\n' % inst)
            return help(ui)
        if command in exts:
            cmd = 'exthelp'
        else:
            cmd = 'topichelp'

    # check to see if we want help on an extension rather than function
    extensionnames = [x for x,y in extensions.extensions()]
    if type(cmd) is tuple and command in extensionnames and cmd[0] != command:
        cmd = 'exthelp'

    def print_command(cmd, cmdinfo):
        if ui.verbose:
            aliases = [cmd]
            aliases.extend(cmdinfo[1])
            line = '  %s:\n      %s' % (', '.join(aliases), (cmdinfo[0].__doc__ or
                    '<missing summary>').splitlines()[0])
        else:
            line = fmt % (cmd, (cmdinfo[0].__doc__ or '<missing summary>').splitlines()[0])
        ui.write('%s\n' % line)

    def print_commands(pred = lambda cmd: True, commands=commands):
        for cmd, cmdinfo in util.iter_dict_sorted(commands):
            if not pred(cmd):
                continue
            print_command(cmd, cmdinfo)

    if not command or not cmd or cmd == (None, None): # global help
        ui.write("Edlund repository manager (version %s)\n" % util.version())
        ui.write("USAGE: repo <command> [options...]\n\n")

        width = max([len(cmd) for cmd in commands.keys() + repoman.help.topics.keys()])
        width = max(width, maxlength)
        fmt = "  %%-%ds  %%s" % width

        ui.write('Repository commands:\n')

        def is_repository_command(cmd):
            return (cmd not in nonforest_commands and
                    cmd not in module_commands and
                    (cmd not in hidden_commands or ui.debugflag))

        def is_other_command(cmd):
            return (cmd in nonforest_commands and
                    (cmd not in hidden_commands or ui.debugflag))

        def is_module_command(cmd):
            return (cmd in module_commands and
                    (cmd not in hidden_commands or ui.debugflag))

        print_commands(is_repository_command)

        ui.write('\nModule commands:\n')
        print_commands(is_module_command)

        ui.write('\nOther commands:\n')

        print_commands(is_other_command)

        if exts:
            ui.write('\nExtensions:\n')
        for ext, desc in exts.iteritems():
            ui.write('%s\n' % (fmt % (ext, desc.splitlines()[0].strip())))

        if repoman.help.topics:
            ui.write('\nAdditional help topics:\n')
            for name, desc in repoman.help.topics.iteritems():
                ui.write('%s\n' % (fmt % (name, util.wrap(desc.splitlines()[0], 80, 4))))

        if not ui.verbose:
            ui.write('\nuse "repo -v help" to show aliases and global options\n')
        else:
            ui.write('\nGlobal options:\n')
            maxlen = max([len(opt[1]) for opt in globaloptions])
            fmt = '  %%2s --%%-%ds  %%s\n' % maxlen
            for short, long, opt, desc in globaloptions:
                ui.write(fmt % ("-%s" % short if short else short, long, desc))

        return

    if cmd == 'exthelp':
        desc = exts[command]

        ui.write('%s\n\n' % util.wrap(desc, 80, 4))

        try:
            mod = extensions.find(command)
        except KeyError:
            raise util.UnknownCommand(command)

        if mod.cmdtable:
            width = max([len(cmd) for cmd in mod.cmdtable])
            fmt = "  %%-%ds  %%s" % width

            ui.write('\nExtension commands:\n')
            print_commands(commands=mod.cmdtable)

        return

    if cmd == 'topichelp':
        desc = repoman.help.topics[command]

        ui.write('%s\n\n' % util.wrap(desc, 80, 4))

        return

    cmd, cmdinfo = cmd[0], cmd[1]
    cmdfn, aliases, options, helptext = cmdinfo
    ui.write('repo %s %s\n\n' % (cmd, helptext))
    if aliases:
        ui.write("aliases: %s\n\n" % ", ".join(aliases))
    ui.write('%s\n\n' % util.wrap(cmdfn.__doc__ if cmdfn.__doc__ else '<no documentation>', 80, 4))
    display_options = [opt for opt in options
            if not opt[3]
            or opt[3] and not opt[3].startswith('HIDDEN:')
            or opt[3] and opt[3].startswith('HIDDEN:') and ui.verbose]
    if display_options:
        width = max([len(opt[1]) for opt in options])
        space = width + 8
        fmt = " %%s%%1s --%%-%ds  %%s" % width
        ui.write("options:\n")

        def strip_meta(text):
            meta_tags = ['HIDDEN']
            for tag in meta_tags:
                if text.startswith(tag + ':'):
                    text = text[len(tag + ':'):]
            return text

        ui.write("\n".join([ fmt % (opt[0] and '-' or ' ', opt[0], opt[1],
                                  util.wrap(strip_meta(opt[3]), 80, space, space).lstrip())
                           for opt in display_options]))
        ui.write('\n')

def init(ui, path='.', name='forest', **opts):
    '''initializes a new empty repository forest.

    If the destination is omitted, the current directory is used.

    If no name is given, the default name will be "forest".
    '''

    try:
        if not os.path.exists(path):
            os.mkdir(path)

        root = mercurial.hg.repository(ui, os.path.join(path, '.root'), create=True)
        repo = mercurial.hg.repository(ui, os.path.join(path, '.repo'), create=True)

        with open(os.path.join(repo.root, 'modules'), 'wb') as f:
            f.write('')
        repo[None].add(['modules'])
        util.commit(repo, 'Created forest', date=opts.get('date'))
        with open(os.path.join(root.root, 'forest'), 'wb') as f:
            f.write(name)
        root[None].add(['forest'])
        util.commit(root, 'Created forest', date=opts.get('date'))
    except:
        if path != '.':
            shutil.rmtree(path)
        else:
            shutil.rmtree('.root')
            shutil.rmtree('.repo')
        raise

def modadd(ui, forest, module, **opts):
    '''adds a new module to the repository forest'''

    if module in forest.get_all_modules():
        raise util.Abort('Module already exists.')

    mercurial.hg.repository(ui, os.path.join(forest.path, module), create=True)
    module_path = forest.modules_lmd_path
    cur_modules = util.try_read_line(module_path, '').rstrip()
    if cur_modules:
        cur_modules += '\r\n'
    util.write_utf8(module_path, cur_modules + module + '\r\n')

    repo = forest.lmd_repo
    if repo.dirstate['modules'] == '?':
        repo.dirstate.add('modules')

    cmsg = 'Added module "%s"' % (module,)
    util.commit(repo, cmsg, date=opts.get('date'))

def modremove(ui, forest, module, **opts):
    '''removes a module from the repository forest'''

    if module not in forest.get_all_modules():
        raise util.Abort('Module does not exist.')

    if not opts['yes']:
        r = ui.prompt('Really remove module "%s" from the forest (y/yes/n/no)?' % module, 'n')
        if r != 'yes' and r != 'y':
            return

    module_path = forest.modules_lmd_path
    cur_modules = util.try_read_lines(module_path)
    cur_modules.remove(module)
    util.write_utf8(module_path, '\r\n'.join(cur_modules) + '\r\n')

    repo = forest.lmd_repo
    cmsg = 'Removed module "%s"' % (module,)
    util.commit(repo, cmsg, date=opts.get('date'))

def unrevert(ui, repo, **opts):
    '''undo a hg revert

    The command finds new .orig files and copy them back to the original.

    This command only operates on the current module.
    '''

    orig_files = []
    for root, dirs, files in os.walk(repo.root):
        if '.hg' in dirs:
            dirs.remove('.hg')

        for file in files:
            if os.path.splitext(file)[1] == '.orig':
                orig_files.append(os.path.join(root, file))

    start = time.mktime((datetime.date.today() - datetime.timedelta(days=opts['daysback'])).timetuple())

    orig_files = [f for f in orig_files if os.stat(f).st_mtime >= start]

    for f in orig_files:
        orig = f[:-5]
        ui.status('%s\n' % (util.normpath(ui, orig),))
        if not opts['dry_run']:
            mercurial.util.rename(f, orig)

    if not opts['dry_run']:
        if orig_files:
            ui.status('Unreverted %d files.\n' % len(orig_files))
        else:
            ui.status('Nothing to revert.\n')

def rebase(ui, repo, date=None, **opts):
    '''rebases local commits onto the given destination

    This is typically used after a pull, to move local changes on top of the
    ones pulled in, as an alternative to merge. It should only be used for a
    small number of individual commits; related strings of commits should be
    merged instead. Any uncommitted local changes are automatically shelved,
    rebased and unshelved afterwards.

    This command only operates on the current module.
    '''

    rebase_mod = util.get_mercurial_extension(ui, 'rebase')
    rebase_opts = util.get_mercurial_default_opts('rebase', rebase_mod.cmdtable)

    if opts['continue'] and opts['abort']:
        ui.warn('you can only specify one of --abort or --continue.\n')
        return
    if opts['continue']:
        rebase_opts['continue'] = opts['continue']
        rebase_mod.rebase(ui, repo, **rebase_opts)
        return
    if opts['abort']:
        rebase_opts['abort'] = opts['abort']
        rebase_mod.rebase(ui, repo, **rebase_opts)
        return

    src = repo['.']
    dst = repo['tip'] if not opts['dest'] else repo[opts['dest']]
    if src == dst:
        raise util.Abort('cannot rebase a changeset on itself; maybe you need to use the --dest option?')

    if not opts['dest'] and src.branch() != dst.branch():
        raise util.Abort('cannot rebase to branch %s from branch %s without explicit --dest option' %
                         (dst.branch(), src.branch()))

    heads = [repo[h].rev() for h in repo.heads()]
    if src.rev() not in heads or dst.rev() not in heads:
        raise util.Abort('source or destination, or both, are not head revisions')

    ancestor = src.ancestor(dst)

    mergenodes = [repo[n].rev() for n in repo.changelog.nodesbetween(
        [ancestor.node()], [src.node()])[0] if len(repo[n].parents()) > 1 and n != ancestor.node()]
    if mergenodes:
        raise util.Abort('unable to rebase merge changeset %d - use hg merge instead' % max(mergenodes))

    if ancestor == mercurial.node.nullid:
        raise util.Abort('source and destination have no common ancestor')

    ui.status('Checking for local changes... ')
    modified, added, removed, deleted, unknown, ignored, clean = repo.status()
    if modified:
        ui.status('found some; saving them\n')
        util.commit(repo, 'REBASE: local changes')
    else:
        ui.status('none found\n')

    ui.note('creating backup bundle\n')
    bundle_opts = util.get_mercurial_default_opts('bundle')
    bundle_opts['base'] = [str(ancestor.rev())]
    mercurial.commands.bundle(ui, repo, '%s/.rebase-%s-to-%s.backup' %
                              (repo.root, src, dst), **bundle_opts)

    if modified or opts['dest']:
        rebase_opts['dest'] = dst.hex()
    abort = False
    try:
        with cmdutil.quietui(ui, repo.ui, filter='saving bundle to '):
            rv = util.docmd_encoding(lambda: rebase_mod.rebase(ui, repo, **rebase_opts))
        if not rv:
            ui.write('rebase completed\n')
        elif rv == 1:
            ui.warn('nothing to rebase\n')
        else:
            ui.warn('rebase failed\n')
    except Exception, e:
        ui.warn('unable to rebase: %s\n' % e)
    if modified:
        ctx = repo['.']
        cmdutil.combine_changesets(repo, [ctx])
        cmdutil.strip(ui, repo, ctx.hex())


def combine(ui, repo, rev, **opts):
    '''combines changesets and possibly local changes

    Combines all changesets from the current working directory parent to the
    given revision (both included), into a single new changeset. Combine can
    only be safely used on unpushed changesets.

    This command only operates on the current repository module.
    '''

    # Prepare.
    if not rev:
        raise util.Abort('please specify a revision to combine with')
    if not opts['workingdir']:
        if any(repo.status()[:4]):
            raise util.Abort('uncommitted changes found; use the -w option to combine those as well')
    tctx = repo[rev]
    trev = tctx.rev()

    # Detect foreign merges and build graph set.
    cl = repo.changelog
    stack = [cl.rev(n) for n in repo.dirstate.parents() if n != nullid]
    graph = set()
    while stack:
        r = stack.pop()
        if r < trev:
            raise util.Abort('foreign merges in changesets or non-ancestral revision given')
        graph.add(r)
        if r > trev:
            stack.extend(p for p in cl.parentrevs(r) if p != -1)

    # Detect unrelated children.
    for r in xrange(len(cl) - 1, trev, -1):
        if r not in graph:
            parents = cl.parentrevs(r)
            if parents[0] in graph or parents[1] in graph:
                raise util.Abort('unrelated changesets would be removed; please combine complete graphs')

    # Build list of contexts.
    ctxs = []
    cctx = repo[None].p1()
    while cctx.rev() >= trev:
        ctxs.append(cctx)
        cctx = cctx.p1()

    # Backup and combine.
    if not opts['keep'] and not opts['nobackup']:
        bundle_opts = util.get_mercurial_default_opts('bundle')
        bundle_opts['base'] = [str(tctx.p1().rev())]
        bundle_opts['rev'] = ['.']
        mercurial.commands.bundle(ui, repo, '%s/.combine-to-%s.backup' %
                                  (repo.root, tctx), **bundle_opts)
    cmdutil.combine_changesets(repo, ctxs)

    # Strip and commit.
    if not opts['keep']:
        cmdutil.strip(ui, repo, tctx.hex())
    if not opts['nocommit']:
        mercurial.util.system('hgtk commit', cwd=repo.root,
                onerr=util.Abort, errprefix='commit failed')


def uncommit(ui, repo, **opts):
    '''removes the given head commit

    Removes the given head commit (which must be a working directory parent) and
    keeps the modifications in the source files for a subsequent recommit or
    similar. Care must be taken if any of the committed files have been modified
    after committing. This command is useful to fix incorrect commit messages or
    changes, but should of course only be used on unpushed commits.

    This command only operates on the current repository module.
    '''

    # Validate arguments and state
    wdirp = repo[None].parents()
    if not opts['rev']:
        if len(wdirp) > 1:
            raise util.Abort('working directory has more than one parent; '
                             'please specify the revision to uncommit')
        rev = wdirp[0]
    else:
        rev = repo[opts['rev']]
        if rev != wdirp[0] and (len(wdirp) == 1 or rev != wdirp[1]):
            raise util.Abort('specified revision must be a working directory parent')

    if not rev.rev() in [repo[h].rev() for h in repo.heads()]:
        raise util.Abort('specified revision is not a repository head')

    # Remove and strip commit
    cmdutil.combine_changesets(repo, [rev])
    cmdutil.strip(ui, repo, rev.hex())

    # Display new state
    ui.status('Uncommit complete. New working dir parents:\n')
    displayer = mercurial.cmdutil.show_changeset(ui, repo, {})
    wctx = repo[None]
    displayer.show(wctx.p1())
    p2 = wctx.p2()
    if p2.node() != nullid:
        displayer.show(p2)
    displayer.close()


def vclone(ui, source, solution, dest=None, **opts):
    '''creates a virtual clone of the given solution from the given source

    In a virtual clone, all files are shared with the source; this is achieved
    using symbolic links. The source must be a local directory.'''

    # Sanity checks.
    if not dest:
        dest = solution
    if os.path.exists(dest):
        raise util.Abort('destination already exists.')
    sf = _forest.Forest(ui, source)
    if sf.solution and sf.solution != solution:
        raise util.Abort("source is a '%s' forest and can't be cloned as a '%s' forest." % (sf.solution, solution))
    if not sf.solution:
        modules, solution = sf.get_solution_modules(solution)
        if not modules:
            raise util.Abort('solution %s not found' % solution)
    else:
        modules = sf.modules

    # Clone and adjust metadata.
    ui.write_header('Creating virtual clone of solution %s in %s (from %s)\n' %
                    (solution, util.normpath(ui, os.path.abspath(dest)), util.normpath(ui, os.path.abspath(source))))
    df = cmdutil.preclone(ui, source, dest, symlink=True)
    if not sf.solution:
        df.modules = modules
        df.solution = solution
    df.virtual = source
    util.commit(df.lmd_repo, 'Virtual clone of %s' % source)
    df.branch = sf.branch

    # Fetch missing modules, if any.
    missing = set(df.modules) - set(sf)
    if missing:
        ui.status('Cloning missing modules:\n')
        cmdutil.pull_metadata(sf)
        sf.clone_modules(missing, branches=[df.branch], initial=False)
        util.commit(sf.lmd_repo, 'Added missing modules')

    # Symlink modules.
    ui.status('Creating symbolic links\n')
    for mod in df.modules:
        util.symlink(os.path.join(source, mod), os.path.join(dest, mod))

def extend(ui, f, source=None, module=None):
    '''extends a forest with extra modules

    When cloning the specified modules only the current branch will be cloned.
    Other branches can then be pulled in normally.
    '''

    if not module:
        raise util.Abort('you must specify at least one module to extend the forest with')
    existing = util.sortmodules(mod for mod in module if os.path.exists(os.path.join(f.root, mod)))
    if existing:
        raise util.Abort('the following modules already exist locally: %s' % (', '.join(existing)))
    remotemods = cmdutil.get_remote_info(ui, f.getsource(source=source))
    missing = set(module) - set(remotemods)
    if missing:
        raise util.Abort('the following modules cannot be found: %s' % (', '.join(util.sortmodules(missing))))

    ui.status('Extending forest in %s:\n' % util.normpath(ui, f.root))
    cmdutil.pull_metadata(f, source)
    f.clone_modules(module, branches=[f.branch], initial=False, source=source)

def version(ui, *args, **opts):
    '''shows the version of the Edlund repository manager tool'''

    def _open(ui, url_, data=None):
        u = mercurial.util.url(url_)
        if u.scheme:
            u.scheme = u.scheme.lower()
            url_, authinfo = u.authinfo()
        else:
            path = mercurial.util.normpath(os.path.abspath(url_))
            url_ = 'file://' + urllib.pathname2url(path)
            authinfo = None
        opener = mercurial.url.opener(ui, authinfo)
        del opener.addheaders[-1]
        return opener.open(url_, data)

    repo_version = util.version()

    if opts.get('check'):
        version_url = ui.config('repo-ui', 'version_url')
        if not version_url:
            ui.warn('version check not possible due to missing version_url in the repo-ui section\n')
            return

        try:
            data = json.load(_open(ui, version_url))
            products = data['products']
            remote_version = tolocal(products['repoman'].encode('utf-8'))
            download_url = data.get('download_url')
            message = data.get('message')
            if message:
                message = tolocal(message.encode('utf-8'))
        except Exception, e:
            raise util.Abort('error getting version info: %s' % str(e))

        if repo_version != remote_version:
            ui.warn('RepoMan is out of date; the newest version is %s (local version is %s)\n' %
                    (remote_version, repo_version))
            if download_url:
                ui.write('Download the new version here: ', download_url, '\n')
            if message:
                ui.write('\n', message, '\n\n')
            return 1

    else:
        hg_version = mercurial.util.version()
        thg_version = thgversion()
        versions = [
            ('RepoMan', repo_version),
            ('TortoiseHg', thg_version),
            ('Mercurial', hg_version),
        ]
        fmt = ui.emph_str('%%-%ds  ') % max(len(x[0]) for x in versions)
        for tool, version in versions:
            ui.write(fmt % tool, version, '\n')

def vstatus(ui, f, no_unknown=False):
    '''presents hgtk status for each module with changes or unknown files'''

    found_changes = False

    for mod in f:
        repo = f[mod]
        modified, added, removed, deleted, unknown = repo.status(unknown=(not no_unknown))[0:5]
        if modified or added or removed or deleted or unknown:
            mercurial.util.system('hgtk status', cwd=repo.root,
                    onerr=util.Abort, errprefix='status failed')
            found_changes = True

    if not found_changes:
        ui.status('no changes found\n')

def undo(ui, f, yes=False):
    '''undoes the last operation; only applies to some operations

    In particular, the following is a complete list of undoable operations:
    - pull
    - merge commits and commits with --message
    - branch manipulation
    
    Note that any push will clear the undo information, preventing undo.'''

    # Verify undo information
    operation, description, extra, modules, correct = f.read_undo()
    modules &= set(f) | set([f.GMD])
    ui.status('operation: %s\n' % description)
    ui.status('involved modules: %s\n' % ', '.join(util.sortmodules(['(metadata)' if mod == f.GMD else mod for mod in modules])))
    wrong = modules - correct
    if wrong:
        ui.warn('The following modules have changed and cannot be included: %s\n' % ', '.join(util.sortmodules(wrong)))
    if not yes:
        answer = ui.prompt('Undo this %s (y/yes/n/no)?' % operation, 'n')
        if answer not in ['y', 'yes']:
            ui.status('undo aborted.\n')
            return

    # Perform rollbacks
    modules &= correct
    modstr = cmdutil.modstr_tmpl(ui, modules, metadata=(f.GMD in modules))
    ui.filter = re.compile('^working directory now based')
    for mod in util.sortmodules(modules):
        md = mod == f.GMD
        ui.write(modstr % ('(metadata)' if md else mod))
        repo = f[mod]
        repo.ui.filter = ui.filter
        if md:
            if os.path.exists(repo.sjoin('repoman.undo')):
                for hg_undo, repo_undo in f.get_gmd_undo_files():
                    mercurial.util.rename(repo_undo, hg_undo)
        repo.rollback()
        if md and operation != 'pull':
            # Clean-update and purge metadata
            st = repo.status(unknown=True)
            if st[0] or st[1] or st[2] or st[3]:
                with cmdutil.quietui(repo.ui):
                    mercurial.hg.clean(repo, 'tip', show_stats=False)
            for file in st[1] + st[4]:
                    try:
                        os.unlink(repo.wjoin(file))
                    except OSError:
                        pass

    # Perform additional undo steps
    if operation.startswith('branch'):
        branch = extra[0]
        f.branch = branch
        for mod in f:
            f[mod].dirstate.setbranch(branch)
    f.clear_undo()

def bclone(ui, source, dest):
    '''make a clone of a complete forest bundle'''

    srepo = _forest.Bundle(source)
    if os.path.exists(dest) and os.listdir(dest):
        raise util.Abort('destination already exists')

    if not os.path.exists(dest):
        util.mkdir_rec(dest)

    for mod in srepo.modules:
        fdest = os.path.join(dest, mod + '.hg')
        srepo.get(mod, fdest)
        mercurial.commands.clone(ui, fdest, os.path.join(dest, mod))
        mercurial.util.unlink(fdest)

    f = _forest.Forest(ui, repository=dest)
    for mod in f.modules:
        if mod not in f:
            mercurial.commands.init(ui, os.path.join(dest, mod))


#
# command => (aliases, options, description)
#
commands = {
    'bclone': (bclone, [], [], 'FILE DEST'),
    'bundle': (bundle, [], [
        ('b', 'branch', [], 'branch to bundle (defaults to working branch)'),
        ('f', 'force', False, 'compare even if destination is unrelated'),
        ('', 'current', False, 'HIDDEN: consider only the current head of each module'),
        ('', 'strip', False, 'strip bundled changesets after bundling'),
        ('', 'noninteractive', False, 'HIDDEN: assume yes on all questions'),
        ('', 'all', False, 'HIDDEN: bundle entire forest'),
        ], '[-b BRANCH]... FILE [DEST]'),
    'modadd': (modadd, [], [
        ('d', 'date', '', 'HIDDEN: record datecode as commit date'),
        ], 'MODULE'),
    'status': (status, ['st'], [
        ('m', 'modified', False, 'display modified files'),
        ('a', 'added',    False, 'display added files'),
        ('r', 'removed',  False, 'display removed files'),
        ('d', 'deleted',  False, 'display deleted files'),
        ('u', 'unknown',  False, 'display unknown files')], ''),
    'help': (help, [], [], '[COMMAND]'),
    'heads': (heads, [], [
        ('', 'template', '', 'display with template'),
        ('a', 'all', None, 'show all heads on all branches')], ''),
    'info': (info, [], [], ''),
    'init': (init, [], [
        ('d', 'date', '', 'HIDDEN: record datecode as commit date'), 
        ], '[DEST] [NAME]'),
    'outgoing': (outgoing, ['out'], [
        ('', 'current', False, 'consider only the current head of each module'),
        ('b', 'branch', [], 'branches to show (defaults to working branch)'),
        ('', 'force', False, 'show outgoing against unrelated repository'),
        ('', 'style', '', 'display using template map file'),
        ('', 'template', '', 'display with template'),
        ], '[-b BRANCH]... [DEST]'),
    'push': (push, [], [
        ('', 'current', False, 'HIDDEN: consider only the current head of each module'),
        ('b', 'branch', [], 'branches to push (defaults to working branch)'),
        ('', 'force', False, 'HIDDEN: enable creation of new heads on the remote (use with extreme caution!)'),
        ('', 'noninteractive', False, 'HIDDEN: assume yes on all questions'),
        ('', 'style', '', 'display using template map file'),
        ('', 'template', '', 'display using template'),
        ('', 'no-metadata-pull', False, 'HIDDEN: do not pull metadata changes before pushing'),
        ], '[-b BRANCH]... [DEST]'),
    'incoming': (incoming, ['in'], [
        ('b', 'branch', [], 'provide a list of branches to show (defaults to the working branch, or all branches for bundles)'),
        ('', 'current', False, 'use the current repository branch instead of the working branch (only useful when -b is not used)'),
        ('', 'modmap', [], 'HIDDEN: (usage: --modmap DEST=SOURCE) pull module DEST from module SOURCE, augmenting branches locally as necessary.'),
        ('', 'style', '', 'display using template map file'),
        ('', 'template', '', 'display with template'),
        ('l', 'log', False, 'view graphical changelog with incoming changesets'),
        ], '[-b BRANCH]... [-l] [SOURCE]'),
    'parents': (parents, [], [
        ('', 'template', '', 'display with template'),
        ('', 'style', '', 'display with style'),
        ], ''),
    'paths': (paths, [], [
        ('', 'add', [], 'add NAME as alias for PATH (replaces existing binding for NAME)'),
        ('', 'remove', [], 'remove alias NAME, if present'),
        ], '[--add NAME=PATH | --remove NAME]'),
    'update': (update, ['up'], [
        ('b', 'branch', '', 'branch to update to'),
        ('', 'base', False, 'update to base of branch instead of tip'),
        ('C', 'clean', False, 'overwrite locally modified files (with backup); also needed to switch between heads on the same branch'),
        ('', 'nobackup', False, 'don\'t backup when using --clean'),
        ('m', 'merge', False, 'merge local changes when updating'),
        ('', 'local', False, 'allow updating to non-global branches, bookmarks and tags'),
        ('', 'partial', False, 'allow partial updates, if not all modules can be updated'),
        ('d', 'date', '', 'date specification for matching changesets to update to'),
        ('', 'delta', 3600, 'time delta in seconds (defaults to 1 hour, only works with --date)'),
        ], '[[-b] BRANCH] [-m] [-C]'),
    'metadata': (metadata, ['md'], [
        ('s', 'solutions', False, 'display all available solutions'),
        ('b', 'branches', '', 'display available branches matching the pattern'),
        ('S', 'show-modules', False, 'include list of modules in metadata'),
        ('d', 'date', False, 'show dates where the branch was created/moved/extended'),
        ], '[-s | -b PATTERN] [-S]'),
    'serve': (serve, [], [
        ('p', 'port', 8000, 'port to listen on (default: 8000)'),
        ('', 'allow-push', False, 'allow users to push to your served forest'),
        ], '[-p PORT]'),
    'clone': (clone, [], [
        ('b', 'branch', [], 'branch to retrieve'),
        ('U', 'noupdate', False, 'do not create a working copy'),
        ('s', 'solution', '', 'solution to retrieve'),
        ('d', 'dest', '', 'destination directory name; derived from solution or source by default'),
        ('e', 'empty', False, 'clone an empty module collection'),
        ('x', 'detach', False, 'keep the source\'s default upstream path'),
        ('M', 'module', [], 'module to clone'),
        ], 'SOURCE ([-s] SOLUTION | -M MODULE... | -e) -b BRANCH... [-d DEST] [-U] [-x]'),
    'unclone': (unclone, [], [
        ('', 'force', False, "remove target even if it doesn't look like a cloned solution or module forest"),
        ], 'PATH'),
    'commit': (commit, ['ci'], [
        ('m', 'message', False, 'prompt for commit message to use for all modules (note that no file selection will be possible when this option is used)'),
        ('d', 'date', '', 'HIDDEN: record datecode as commit date'),
        ], '[-m]'),
    'branch': (branch, [], [
        ('c', 'create', False, 'create a new branch'),
        ('e', 'extend', False, 'extend an existing branch to new modules'),
        ('m', 'move', False, 'HIDDEN: move (re-use) an existing, inactive, branch'),
        ('', 'root', False, 'HIDDEN: allow the creation of a root namespace'),
        ('d', 'date', '', 'HIDDEN: record datecode as commit date'),
        ('',  'null', False, 'HIDDEN: allow branch creation without working copy'),
        ], '[-c | -e] BRANCH'),
    'merge': (merge, [], [
        ('n', 'dry-run', False, 'do not perform actions, just print output'),
        ('', 'no-status', False, 'do not display merge review status windows'),
        ], '[-n] BRANCH'),
    'modremove': (modremove, ['modrm'], [
        ('d', 'date', '', 'HIDDEN: record datecode as commit date'),
        ('', 'yes', False, 'answer yes to all questions'),
        ], '[MODULE]'),
    'unrevert': (unrevert, [], [
        ('n', 'dry-run', False, 'do not perform actions, just print output'),
        ('', 'daysback', 0, 'number of days to look back'),
        ], ''),
    'rebase': (rebase, [], [
        ('d', 'dest', '', 'destination revision to rebase onto (defaults to tip)'),
        ('', 'continue', False, 'continue an interrupted rebase (typically non-trivial merge)'),
        ('', 'abort', False, 'abort an interrupted rebase and restore the revision graph'),
        ('', 'date', '', 'HIDDEN: record datecode as commit date on queues'),
        ], '[--dest DEST | --continue | --abort]'),
    'uncommit': (uncommit, ['unci'], [
        ('r', 'rev', '', 'revision to uncommit (must be a head revision; defaults to parent revision)'),
        ], '[-r REV]'),
    'pull': (pull, ['unbundle'], [
        ('b', 'branch', [], 'branch to pull (defaults to the current working branch, or all branches for bundles)'),
        ('', 'current', False, 'use the current repository branch instead of the working branch; can\'t be used with -b'),
        ('', 'modmap', [], 'HIDDEN: (usage: --modmap DEST=SOURCE) pull module DEST from module SOURCE, augmenting branches locally as necessary.'),
        ('U', 'noupdate', False, 'do not perform update after pull'),
        ('C', 'clean', False, 'overwrite locally modified files (with backup); also needed to switch between heads on the same branch'),
        ], '[-U] [-b BRANCH]... [SOURCE]'),
    'vclone': (vclone, [], [
        ], 'SOURCE SOLUTION [DEST]'),
    'version': (version, [], [
        ('', 'check', False, 'check whether the latest version is installed'),
        ], ''),
    'vstatus': (vstatus, ['vst'], [
        ('U', 'no-unknown', False, 'skip modules with only unknown files'),
        ], ''),
    'undo': (undo, [], [
        ('', 'yes', False, 'assume yes on all questions'),
        ], ''),
    'extend': (extend, [], [('M', 'module', [], 'module to extend with')],
            '-M MODULE... [SOURCE]'),
    'combine': (combine, [], [
        ('w', 'workingdir', False, 'combine with working directory changes as well'),
        ('k', 'keep', False, 'keep original commits'),
        ('C', 'nocommit', False, 'don\'t commit the resulting changes'),
        ('', 'nobackup', False, 'don\'t backup old commits'),
        ], 'REV [-w] [-k] [-C]'),
}

globaloptions = [
    ('R', 'repository', '', 'operate on this repository (or module, for module commands)'),
    ('M', 'module', [], 'include this module (can be repeated)'),
    ('N', 'notmodule', [], 'exclude this module (can be repeated)'),
    ('v', 'verbose', None, 'enable additional output'),
    ('q', 'quiet', None, 'suppress output'),
    ('', 'debug', None, 'enable debugging output'),
    ('', 'debugger', None, 'enable built-in debugger'),
    ('', 'traceback', None, 'enable traceback output'),
    ('', 'time', None, 'time how long the command takes'),
    ('', 'simpleui', None, 'suppress color output'),
    ('', 'config', [], 'override/set configuration variable'),
    ('', 'version', None, 'show repoman version'),
    ('', 'help', None, 'display help for the command'),
    ('', 'color', '', 'when to colorize (always, auto, or never)'),
]

nonforest_commands = ['help', 'init', 'clone', 'unclone', 'vclone', 'version', 'bclone']
hidden_commands = ['init', 'modadd', 'modremove', 'bclone']
module_commands = ['unrevert', 'rebase', 'uncommit', 'combine']
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.