~bzr-pqm/bzr/bzr.dev

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
# Copyright (C) 2004, 2005 by Canonical Ltd

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""builtin bzr commands"""


import errno
import os
from shutil import rmtree
import sys

import bzrlib
import bzrlib.branch
from bzrlib.branch import Branch
import bzrlib.bzrdir as bzrdir
from bzrlib.commands import Command, display_command
from bzrlib.revision import common_ancestor
import bzrlib.errors as errors
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError, 
                           NotBranchError, DivergedBranches, NotConflicted,
                           NoSuchFile, NoWorkingTree, FileInWrongBranch)
from bzrlib.log import show_one_log
from bzrlib.merge import Merge3Merger
from bzrlib.option import Option
from bzrlib.progress import DummyProgress
from bzrlib.revisionspec import RevisionSpec
import bzrlib.trace
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
from bzrlib.transport.local import LocalTransport
import bzrlib.ui
from bzrlib.workingtree import WorkingTree


def tree_files(file_list, default_branch=u'.'):
    try:
        return internal_tree_files(file_list, default_branch)
    except FileInWrongBranch, e:
        raise BzrCommandError("%s is not in the same branch as %s" %
                             (e.path, file_list[0]))

def internal_tree_files(file_list, default_branch=u'.'):
    """\
    Return a branch and list of branch-relative paths.
    If supplied file_list is empty or None, the branch default will be used,
    and returned file_list will match the original.
    """
    if file_list is None or len(file_list) == 0:
        return WorkingTree.open_containing(default_branch)[0], file_list
    tree = WorkingTree.open_containing(file_list[0])[0]
    new_list = []
    for filename in file_list:
        try:
            new_list.append(tree.relpath(filename))
        except errors.PathNotChild:
            raise FileInWrongBranch(tree.branch, filename)
    return tree, new_list


# TODO: Make sure no commands unconditionally use the working directory as a
# branch.  If a filename argument is used, the first of them should be used to
# specify the branch.  (Perhaps this can be factored out into some kind of
# Argument class, representing a file in a branch, where the first occurrence
# opens the branch?)

class cmd_status(Command):
    """Display status summary.

    This reports on versioned and unknown files, reporting them
    grouped by state.  Possible states are:

    added
        Versioned in the working copy but not in the previous revision.

    removed
        Versioned in the previous revision but removed or deleted
        in the working copy.

    renamed
        Path of this file changed from the previous revision;
        the text may also have changed.  This includes files whose
        parent directory was renamed.

    modified
        Text has changed since the previous revision.

    unchanged
        Nothing about this file has changed since the previous revision.
        Only shown with --all.

    unknown
        Not versioned and not matching an ignore pattern.

    To see ignored files use 'bzr ignored'.  For details in the
    changes to file texts, use 'bzr diff'.

    If no arguments are specified, the status of the entire working
    directory is shown.  Otherwise, only the status of the specified
    files or directories is reported.  If a directory is given, status
    is reported for everything inside that directory.

    If a revision argument is given, the status is calculated against
    that revision, or between two revisions if two are provided.
    """
    
    # TODO: --no-recurse, --recurse options
    
    takes_args = ['file*']
    takes_options = ['all', 'show-ids', 'revision']
    aliases = ['st', 'stat']
    
    @display_command
    def run(self, all=False, show_ids=False, file_list=None, revision=None):
        tree, file_list = tree_files(file_list)
            
        from bzrlib.status import show_tree_status
        show_tree_status(tree, show_unchanged=all, show_ids=show_ids,
                         specific_files=file_list, revision=revision)


class cmd_cat_revision(Command):
    """Write out metadata for a revision.
    
    The revision to print can either be specified by a specific
    revision identifier, or you can use --revision.
    """

    hidden = True
    takes_args = ['revision_id?']
    takes_options = ['revision']
    
    @display_command
    def run(self, revision_id=None, revision=None):

        if revision_id is not None and revision is not None:
            raise BzrCommandError('You can only supply one of revision_id or --revision')
        if revision_id is None and revision is None:
            raise BzrCommandError('You must supply either --revision or a revision_id')
        b = WorkingTree.open_containing(u'.')[0].branch
        if revision_id is not None:
            sys.stdout.write(b.repository.get_revision_xml(revision_id))
        elif revision is not None:
            for rev in revision:
                if rev is None:
                    raise BzrCommandError('You cannot specify a NULL revision.')
                revno, rev_id = rev.in_history(b)
                sys.stdout.write(b.repository.get_revision_xml(rev_id))
    

class cmd_revno(Command):
    """Show current revision number.

    This is equal to the number of revisions on this branch."""
    takes_args = ['location?']
    @display_command
    def run(self, location=u'.'):
        print Branch.open_containing(location)[0].revno()


class cmd_revision_info(Command):
    """Show revision number and revision id for a given revision identifier.
    """
    hidden = True
    takes_args = ['revision_info*']
    takes_options = ['revision']
    @display_command
    def run(self, revision=None, revision_info_list=[]):

        revs = []
        if revision is not None:
            revs.extend(revision)
        if revision_info_list is not None:
            for rev in revision_info_list:
                revs.append(RevisionSpec(rev))
        if len(revs) == 0:
            raise BzrCommandError('You must supply a revision identifier')

        b = WorkingTree.open_containing(u'.')[0].branch

        for rev in revs:
            revinfo = rev.in_history(b)
            if revinfo.revno is None:
                print '     %s' % revinfo.rev_id
            else:
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)

    
class cmd_add(Command):
    """Add specified files or directories.

    In non-recursive mode, all the named items are added, regardless
    of whether they were previously ignored.  A warning is given if
    any of the named files are already versioned.

    In recursive mode (the default), files are treated the same way
    but the behaviour for directories is different.  Directories that
    are already versioned do not give a warning.  All directories,
    whether already versioned or not, are searched for files or
    subdirectories that are neither versioned or ignored, and these
    are added.  This search proceeds recursively into versioned
    directories.  If no names are given '.' is assumed.

    Therefore simply saying 'bzr add' will version all files that
    are currently unknown.

    Adding a file whose parent directory is not versioned will
    implicitly add the parent, and so on up to the root. This means
    you should never need to explictly add a directory, they'll just
    get added when you add a file in the directory.

    --dry-run will show which files would be added, but not actually 
    add them.
    """
    takes_args = ['file*']
    takes_options = ['no-recurse', 'dry-run', 'verbose']

    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False):
        import bzrlib.add

        if dry_run:
            if is_quiet():
                # This is pointless, but I'd rather not raise an error
                action = bzrlib.add.add_action_null
            else:
                action = bzrlib.add.add_action_print
        elif is_quiet():
            action = bzrlib.add.add_action_add
        else:
            action = bzrlib.add.add_action_add_and_print

        added, ignored = bzrlib.add.smart_add(file_list, not no_recurse, 
                                              action)
        if len(ignored) > 0:
            for glob in sorted(ignored.keys()):
                match_len = len(ignored[glob])
                if verbose:
                    for path in ignored[glob]:
                        print "ignored %s matching \"%s\"" % (path, glob)
                else:
                    print "ignored %d file(s) matching \"%s\"" % (match_len,
                                                              glob)
            print "If you wish to add some of these files, please add them"\
                " by name."


class cmd_mkdir(Command):
    """Create a new versioned directory.

    This is equivalent to creating the directory and then adding it.
    """
    takes_args = ['dir+']

    def run(self, dir_list):
        for d in dir_list:
            os.mkdir(d)
            wt, dd = WorkingTree.open_containing(d)
            wt.add([dd])
            print 'added', d


class cmd_relpath(Command):
    """Show path of a file relative to root"""
    takes_args = ['filename']
    hidden = True
    
    @display_command
    def run(self, filename):
        tree, relpath = WorkingTree.open_containing(filename)
        print relpath


class cmd_inventory(Command):
    """Show inventory of the current working copy or a revision.

    It is possible to limit the output to a particular entry
    type using the --kind option.  For example; --kind file.
    """
    takes_options = ['revision', 'show-ids', 'kind']
    
    @display_command
    def run(self, revision=None, show_ids=False, kind=None):
        if kind and kind not in ['file', 'directory', 'symlink']:
            raise BzrCommandError('invalid kind specified')
        tree = WorkingTree.open_containing(u'.')[0]
        if revision is None:
            inv = tree.read_working_inventory()
        else:
            if len(revision) > 1:
                raise BzrCommandError('bzr inventory --revision takes'
                    ' exactly one revision identifier')
            inv = tree.branch.repository.get_revision_inventory(
                revision[0].in_history(tree.branch).rev_id)

        for path, entry in inv.entries():
            if kind and kind != entry.kind:
                continue
            if show_ids:
                print '%-50s %s' % (path, entry.file_id)
            else:
                print path


class cmd_move(Command):
    """Move files to a different directory.

    examples:
        bzr move *.txt doc

    The destination must be a versioned directory in the same branch.
    """
    takes_args = ['source$', 'dest']
    def run(self, source_list, dest):
        tree, source_list = tree_files(source_list)
        # TODO: glob expansion on windows?
        tree.move(source_list, tree.relpath(dest))


class cmd_rename(Command):
    """Change the name of an entry.

    examples:
      bzr rename frob.c frobber.c
      bzr rename src/frob.c lib/frob.c

    It is an error if the destination name exists.

    See also the 'move' command, which moves files into a different
    directory without changing their name.
    """
    # TODO: Some way to rename multiple files without invoking 
    # bzr for each one?"""
    takes_args = ['from_name', 'to_name']
    
    def run(self, from_name, to_name):
        tree, (from_name, to_name) = tree_files((from_name, to_name))
        tree.rename_one(from_name, to_name)


class cmd_mv(Command):
    """Move or rename a file.

    usage:
        bzr mv OLDNAME NEWNAME
        bzr mv SOURCE... DESTINATION

    If the last argument is a versioned directory, all the other names
    are moved into it.  Otherwise, there must be exactly two arguments
    and the file is changed to a new name, which must not already exist.

    Files cannot be moved between branches.
    """
    takes_args = ['names*']
    def run(self, names_list):
        if len(names_list) < 2:
            raise BzrCommandError("missing file argument")
        tree, rel_names = tree_files(names_list)
        
        if os.path.isdir(names_list[-1]):
            # move into existing directory
            for pair in tree.move(rel_names[:-1], rel_names[-1]):
                print "%s => %s" % pair
        else:
            if len(names_list) != 2:
                raise BzrCommandError('to mv multiple files the destination '
                                      'must be a versioned directory')
            tree.rename_one(rel_names[0], rel_names[1])
            print "%s => %s" % (rel_names[0], rel_names[1])
            
    
class cmd_pull(Command):
    """Pull any changes from another branch into the current one.

    If there is no default location set, the first pull will set it.  After
    that, you can omit the location to use the default.  To change the
    default, use --remember.

    This command only works on branches that have not diverged.  Branches are
    considered diverged if both branches have had commits without first
    pulling from the other.

    If branches have diverged, you can use 'bzr merge' to pull the text changes
    from one into the other.  Once one branch has merged, the other should
    be able to pull it again.

    If you want to forget your local changes and just update your branch to
    match the remote one, use --overwrite.
    """
    takes_options = ['remember', 'overwrite', 'revision', 'verbose']
    takes_args = ['location?']

    def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
        # FIXME: too much stuff is in the command class        
        tree_to = WorkingTree.open_containing(u'.')[0]
        stored_loc = tree_to.branch.get_parent()
        if location is None:
            if stored_loc is None:
                raise BzrCommandError("No pull location known or specified.")
            else:
                print "Using saved location: %s" % stored_loc
                location = stored_loc

        br_from = Branch.open(location)
        br_to = tree_to.branch

        if revision is None:
            rev_id = None
        elif len(revision) == 1:
            rev_id = revision[0].in_history(br_from).rev_id
        else:
            raise BzrCommandError('bzr pull --revision takes one value.')

        old_rh = br_to.revision_history()
        count = tree_to.pull(br_from, overwrite, rev_id)

        if br_to.get_parent() is None or remember:
            br_to.set_parent(location)
        note('%d revision(s) pulled.' % (count,))

        if verbose:
            new_rh = tree_to.branch.revision_history()
            if old_rh != new_rh:
                # Something changed
                from bzrlib.log import show_changed_revisions
                show_changed_revisions(tree_to.branch, old_rh, new_rh)


class cmd_push(Command):
    """Push this branch into another branch.
    
    The remote branch will not have its working tree populated because this
    is both expensive, and may not be supported on the remote file system.
    
    Some smart servers or protocols *may* put the working tree in place.

    If there is no default push location set, the first push will set it.
    After that, you can omit the location to use the default.  To change the
    default, use --remember.

    This command only works on branches that have not diverged.  Branches are
    considered diverged if the branch being pushed to is not an older version
    of this branch.

    If branches have diverged, you can use 'bzr push --overwrite' to replace
    the other branch completely.
    
    If you want to ensure you have the different changes in the other branch,
    do a merge (see bzr help merge) from the other branch, and commit that
    before doing a 'push --overwrite'.
    """
    takes_options = ['remember', 'overwrite', 
                     Option('create-prefix', 
                            help='Create the path leading up to the branch '
                                 'if it does not already exist')]
    takes_args = ['location?']

    def run(self, location=None, remember=False, overwrite=False,
            create_prefix=False, verbose=False):
        # FIXME: Way too big!  Put this into a function called from the
        # command.
        from bzrlib.transport import get_transport
        
        tree_from = WorkingTree.open_containing(u'.')[0]
        br_from = tree_from.branch
        stored_loc = tree_from.branch.get_push_location()
        if location is None:
            if stored_loc is None:
                raise BzrCommandError("No push location known or specified.")
            else:
                print "Using saved location: %s" % stored_loc
                location = stored_loc
        try:
            br_to = Branch.open(location)
        except NotBranchError:
            # create a branch.
            transport = get_transport(location).clone('..')
            if not create_prefix:
                try:
                    transport.mkdir(transport.relpath(location))
                except NoSuchFile:
                    raise BzrCommandError("Parent directory of %s "
                                          "does not exist." % location)
            else:
                current = transport.base
                needed = [(transport, transport.relpath(location))]
                while needed:
                    try:
                        transport, relpath = needed[-1]
                        transport.mkdir(relpath)
                        needed.pop()
                    except NoSuchFile:
                        new_transport = transport.clone('..')
                        needed.append((new_transport,
                                       new_transport.relpath(transport.base)))
                        if new_transport.base == transport.base:
                            raise BzrCommandError("Could not creeate "
                                                  "path prefix.")
            br_to = bzrlib.bzrdir.BzrDir.create_branch_convenience(location)
        old_rh = br_to.revision_history()
        try:
            try:
                tree_to = br_to.working_tree()
            except NoWorkingTree:
                # TODO: This should be updated for branches which don't have a
                # working tree, as opposed to ones where we just couldn't 
                # update the tree.
                warning('Unable to update the working tree of: %s' % (br_to.base,))
                count = br_to.pull(br_from, overwrite)
            else:
                count = tree_to.pull(br_from, overwrite)
        except DivergedBranches:
            raise BzrCommandError("These branches have diverged."
                                  "  Try a merge then push with overwrite.")
        if br_from.get_push_location() is None or remember:
            br_from.set_push_location(location)
        note('%d revision(s) pushed.' % (count,))

        if verbose:
            new_rh = br_to.revision_history()
            if old_rh != new_rh:
                # Something changed
                from bzrlib.log import show_changed_revisions
                show_changed_revisions(br_to, old_rh, new_rh)


class cmd_branch(Command):
    """Create a new copy of a branch.

    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.

    To retrieve the branch as of a particular revision, supply the --revision
    parameter, as in "branch foo/bar -r 5".

    --basis is to speed up branching from remote branches.  When specified, it
    copies all the file-contents, inventory and revision data from the basis
    branch before copying anything from the remote branch.
    """
    takes_args = ['from_location', 'to_location?']
    takes_options = ['revision', 'basis']
    aliases = ['get', 'clone']

    def run(self, from_location, to_location=None, revision=None, basis=None):
        if revision is None:
            revision = [None]
        elif len(revision) > 1:
            raise BzrCommandError(
                'bzr branch --revision takes exactly 1 revision value')
        try:
            br_from = Branch.open(from_location)
        except OSError, e:
            if e.errno == errno.ENOENT:
                raise BzrCommandError('Source location "%s" does not'
                                      ' exist.' % to_location)
            else:
                raise
        br_from.lock_read()
        try:
            if basis is not None:
                basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
            else:
                basis_dir = None
            if len(revision) == 1 and revision[0] is not None:
                revision_id = revision[0].in_history(br_from)[1]
            else:
                # FIXME - wt.last_revision, fallback to branch, fall back to
                # None or perhaps NULL_REVISION to mean copy nothing
                # RBC 20060209
                revision_id = br_from.last_revision()
            if to_location is None:
                to_location = os.path.basename(from_location.rstrip("/\\"))
                name = None
            else:
                name = os.path.basename(to_location) + '\n'
            try:
                os.mkdir(to_location)
            except OSError, e:
                if e.errno == errno.EEXIST:
                    raise BzrCommandError('Target directory "%s" already'
                                          ' exists.' % to_location)
                if e.errno == errno.ENOENT:
                    raise BzrCommandError('Parent of "%s" does not exist.' %
                                          to_location)
                else:
                    raise
            try:
                dir = br_from.bzrdir.sprout(to_location, revision_id, basis_dir)
                branch = dir.open_branch()
            except bzrlib.errors.NoSuchRevision:
                rmtree(to_location)
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
                raise BzrCommandError(msg)
            except bzrlib.errors.UnlistableBranch:
                rmtree(to_location)
                msg = "The branch %s cannot be used as a --basis"
                raise BzrCommandError(msg)
            if name:
                branch.control_files.put_utf8('branch-name', name)

            note('Branched %d revision(s).' % branch.revno())
        finally:
            br_from.unlock()


class cmd_checkout(Command):
    """Create a new checkout of an existing branch.

    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.

    To retrieve the branch as of a particular revision, supply the --revision
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
    code.)

    --basis is to speed up checking out from remote branches.  When specified, it
    uses the inventory and file contents from the basis branch in preference to the
    branch being checked out. [Not implemented yet.]
    """
    takes_args = ['branch_location', 'to_location?']
    takes_options = ['revision'] # , 'basis']

    def run(self, branch_location, to_location=None, revision=None, basis=None):
        if revision is None:
            revision = [None]
        elif len(revision) > 1:
            raise BzrCommandError(
                'bzr checkout --revision takes exactly 1 revision value')
        source = Branch.open(branch_location)
        if len(revision) == 1 and revision[0] is not None:
            revision_id = revision[0].in_history(source)[1]
        else:
            revision_id = None
        if to_location is None:
            to_location = os.path.basename(branch_location.rstrip("/\\"))
        try:
            os.mkdir(to_location)
        except OSError, e:
            if e.errno == errno.EEXIST:
                raise BzrCommandError('Target directory "%s" already'
                                      ' exists.' % to_location)
            if e.errno == errno.ENOENT:
                raise BzrCommandError('Parent of "%s" does not exist.' %
                                      to_location)
            else:
                raise
        checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
        bzrlib.branch.BranchReferenceFormat().initialize(checkout, source)
        checkout.create_workingtree(revision_id)


class cmd_renames(Command):
    """Show list of renamed files.
    """
    # TODO: Option to show renames between two historical versions.

    # TODO: Only show renames under dir, rather than in the whole branch.
    takes_args = ['dir?']

    @display_command
    def run(self, dir=u'.'):
        tree = WorkingTree.open_containing(dir)[0]
        old_inv = tree.basis_tree().inventory
        new_inv = tree.read_working_inventory()

        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
        renames.sort()
        for old_name, new_name in renames:
            print "%s => %s" % (old_name, new_name)        


class cmd_update(Command):
    """Update a tree to have the latest code committed to its branch.
    
    This will perform a merge into the working tree, and may generate
    conflicts. If you have any uncommitted changes, you will still 
    need to commit them after the update.
    """
    takes_args = ['dir?']

    def run(self, dir='.'):
        tree = WorkingTree.open_containing(dir)[0]
        tree.lock_write()
        try:
            if tree.last_revision() == tree.branch.last_revision():
                note("Tree is up to date.")
                return
            conflicts = tree.update()
            note('Updated to revision %d.' %
                 (tree.branch.revision_id_to_revno(tree.last_revision()),))
            if conflicts != 0:
                return 1
            else:
                return 0
        finally:
            tree.unlock()


class cmd_info(Command):
    """Show statistical information about a branch."""
    takes_args = ['branch?']
    
    @display_command
    def run(self, branch=None):
        import bzrlib.info
        bzrlib.info.show_bzrdir_info(bzrdir.BzrDir.open_containing(branch)[0])


class cmd_remove(Command):
    """Make a file unversioned.

    This makes bzr stop tracking changes to a versioned file.  It does
    not delete the working copy.
    """
    takes_args = ['file+']
    takes_options = ['verbose']
    aliases = ['rm']
    
    def run(self, file_list, verbose=False):
        tree, file_list = tree_files(file_list)
        tree.remove(file_list, verbose=verbose)


class cmd_file_id(Command):
    """Print file_id of a particular file or directory.

    The file_id is assigned when the file is first added and remains the
    same through all revisions where the file exists, even when it is
    moved or renamed.
    """
    hidden = True
    takes_args = ['filename']
    @display_command
    def run(self, filename):
        tree, relpath = WorkingTree.open_containing(filename)
        i = tree.inventory.path2id(relpath)
        if i == None:
            raise BzrError("%r is not a versioned file" % filename)
        else:
            print i


class cmd_file_path(Command):
    """Print path of file_ids to a file or directory.

    This prints one line for each directory down to the target,
    starting at the branch root."""
    hidden = True
    takes_args = ['filename']
    @display_command
    def run(self, filename):
        tree, relpath = WorkingTree.open_containing(filename)
        inv = tree.inventory
        fid = inv.path2id(relpath)
        if fid == None:
            raise BzrError("%r is not a versioned file" % filename)
        for fip in inv.get_idpath(fid):
            print fip


class cmd_revision_history(Command):
    """Display list of revision ids on this branch."""
    hidden = True
    @display_command
    def run(self):
        branch = WorkingTree.open_containing(u'.')[0].branch
        for patchid in branch.revision_history():
            print patchid


class cmd_ancestry(Command):
    """List all revisions merged into this branch."""
    hidden = True
    @display_command
    def run(self):
        tree = WorkingTree.open_containing(u'.')[0]
        b = tree.branch
        # FIXME. should be tree.last_revision
        for revision_id in b.repository.get_ancestry(b.last_revision()):
            print revision_id


class cmd_init(Command):
    """Make a directory into a versioned branch.

    Use this to create an empty branch, or before importing an
    existing project.

    Recipe for importing a tree of files:
        cd ~/project
        bzr init
        bzr add .
        bzr status
        bzr commit -m 'imported project'
    """
    takes_args = ['location?']
    def run(self, location=None):
        from bzrlib.branch import Branch
        if location is None:
            location = u'.'
        else:
            # The path has to exist to initialize a
            # branch inside of it.
            # Just using os.mkdir, since I don't
            # believe that we want to create a bunch of
            # locations if the user supplies an extended path
            if not os.path.exists(location):
                os.mkdir(location)
        bzrdir.BzrDir.create_standalone_workingtree(location)


class cmd_diff(Command):
    """Show differences in working tree.
    
    If files are listed, only the changes in those files are listed.
    Otherwise, all changes for the tree are listed.

    examples:
        bzr diff
        bzr diff -r1
        bzr diff -r1..2
    """
    # TODO: Allow diff across branches.
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
    #       or a graphical diff.

    # TODO: Python difflib is not exactly the same as unidiff; should
    #       either fix it up or prefer to use an external diff.

    # TODO: If a directory is given, diff everything under that.

    # TODO: Selected-file diff is inefficient and doesn't show you
    #       deleted files.

    # TODO: This probably handles non-Unix newlines poorly.
    
    takes_args = ['file*']
    takes_options = ['revision', 'diff-options']
    aliases = ['di', 'dif']

    @display_command
    def run(self, revision=None, file_list=None, diff_options=None):
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
        try:
            tree1, file_list = internal_tree_files(file_list)
            tree2 = None
            b = None
            b2 = None
        except FileInWrongBranch:
            if len(file_list) != 2:
                raise BzrCommandError("Files are in different branches")

            tree1, file1 = WorkingTree.open_containing(file_list[0])
            tree2, file2 = WorkingTree.open_containing(file_list[1])
            if file1 != "" or file2 != "":
                # FIXME diff those two files. rbc 20051123
                raise BzrCommandError("Files are in different branches")
            file_list = None
        if revision is not None:
            if tree2 is not None:
                raise BzrCommandError("Can't specify -r with two branches")
            if (len(revision) == 1) or (revision[1].spec is None):
                return diff_cmd_helper(tree1, file_list, diff_options,
                                       revision[0])
            elif len(revision) == 2:
                return diff_cmd_helper(tree1, file_list, diff_options,
                                       revision[0], revision[1])
            else:
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
        else:
            if tree2 is not None:
                return show_diff_trees(tree1, tree2, sys.stdout, 
                                       specific_files=file_list,
                                       external_diff_options=diff_options)
            else:
                return diff_cmd_helper(tree1, file_list, diff_options)


class cmd_deleted(Command):
    """List files deleted in the working tree.
    """
    # TODO: Show files deleted since a previous revision, or
    # between two revisions.
    # TODO: Much more efficient way to do this: read in new
    # directories with readdir, rather than stating each one.  Same
    # level of effort but possibly much less IO.  (Or possibly not,
    # if the directories are very large...)
    @display_command
    def run(self, show_ids=False):
        tree = WorkingTree.open_containing(u'.')[0]
        old = tree.basis_tree()
        for path, ie in old.inventory.iter_entries():
            if not tree.has_id(ie.file_id):
                if show_ids:
                    print '%-50s %s' % (path, ie.file_id)
                else:
                    print path


class cmd_modified(Command):
    """List files modified in working tree."""
    hidden = True
    @display_command
    def run(self):
        from bzrlib.delta import compare_trees

        tree = WorkingTree.open_containing(u'.')[0]
        td = compare_trees(tree.basis_tree(), tree)

        for path, id, kind, text_modified, meta_modified in td.modified:
            print path



class cmd_added(Command):
    """List files added in working tree."""
    hidden = True
    @display_command
    def run(self):
        wt = WorkingTree.open_containing(u'.')[0]
        basis_inv = wt.basis_tree().inventory
        inv = wt.inventory
        for file_id in inv:
            if file_id in basis_inv:
                continue
            path = inv.id2path(file_id)
            if not os.access(bzrlib.osutils.abspath(path), os.F_OK):
                continue
            print path
                
        

class cmd_root(Command):
    """Show the tree root directory.

    The root is the nearest enclosing directory with a .bzr control
    directory."""
    takes_args = ['filename?']
    @display_command
    def run(self, filename=None):
        """Print the branch root."""
        tree = WorkingTree.open_containing(filename)[0]
        print tree.basedir


class cmd_log(Command):
    """Show log of this branch.

    To request a range of logs, you can use the command -r begin..end
    -r revision requests a specific revision, -r ..end or -r begin.. are
    also valid.
    """

    # TODO: Make --revision support uuid: and hash: [future tag:] notation.

    takes_args = ['filename?']
    takes_options = [Option('forward', 
                            help='show from oldest to newest'),
                     'timezone', 'verbose', 
                     'show-ids', 'revision',
                     'log-format',
                     'line', 'long', 
                     Option('message',
                            help='show revisions whose message matches this regexp',
                            type=str),
                     'short',
                     ]
    @display_command
    def run(self, filename=None, timezone='original',
            verbose=False,
            show_ids=False,
            forward=False,
            revision=None,
            log_format=None,
            message=None,
            long=False,
            short=False,
            line=False):
        from bzrlib.log import log_formatter, show_log
        import codecs
        assert message is None or isinstance(message, basestring), \
            "invalid message argument %r" % message
        direction = (forward and 'forward') or 'reverse'
        
        # log everything
        file_id = None
        if filename:
            # find the file id to log:

            dir, fp = bzrdir.BzrDir.open_containing(filename)
            b = dir.open_branch()
            if fp != '':
                try:
                    # might be a tree:
                    inv = dir.open_workingtree().inventory
                except (errors.NotBranchError, errors.NotLocalUrl):
                    # either no tree, or is remote.
                    inv = b.basis_tree().inventory
                file_id = inv.path2id(fp)
        else:
            # local dir only
            # FIXME ? log the current subdir only RBC 20060203 
            dir, relpath = bzrdir.BzrDir.open_containing('.')
            b = dir.open_branch()

        if revision is None:
            rev1 = None
            rev2 = None
        elif len(revision) == 1:
            rev1 = rev2 = revision[0].in_history(b).revno
        elif len(revision) == 2:
            if revision[0].spec is None:
                # missing begin-range means first revision
                rev1 = 1
            else:
                rev1 = revision[0].in_history(b).revno

            if revision[1].spec is None:
                # missing end-range means last known revision
                rev2 = b.revno()
            else:
                rev2 = revision[1].in_history(b).revno
        else:
            raise BzrCommandError('bzr log --revision takes one or two values.')

        # By this point, the revision numbers are converted to the +ve
        # form if they were supplied in the -ve form, so we can do
        # this comparison in relative safety
        if rev1 > rev2:
            (rev2, rev1) = (rev1, rev2)

        mutter('encoding log as %r', bzrlib.user_encoding)

        # use 'replace' so that we don't abort if trying to write out
        # in e.g. the default C locale.
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')

        if (log_format == None):
            default = bzrlib.config.BranchConfig(b).log_format()
            log_format = get_log_format(long=long, short=short, line=line, default=default)

        lf = log_formatter(log_format,
                           show_ids=show_ids,
                           to_file=outf,
                           show_timezone=timezone)

        show_log(b,
                 lf,
                 file_id,
                 verbose=verbose,
                 direction=direction,
                 start_revision=rev1,
                 end_revision=rev2,
                 search=message)


def get_log_format(long=False, short=False, line=False, default='long'):
    log_format = default
    if long:
        log_format = 'long'
    if short:
        log_format = 'short'
    if line:
        log_format = 'line'
    return log_format


class cmd_touching_revisions(Command):
    """Return revision-ids which affected a particular file.

    A more user-friendly interface is "bzr log FILE"."""
    hidden = True
    takes_args = ["filename"]
    @display_command
    def run(self, filename):
        tree, relpath = WorkingTree.open_containing(filename)
        b = tree.branch
        inv = tree.read_working_inventory()
        file_id = inv.path2id(relpath)
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
            print "%6d %s" % (revno, what)


class cmd_ls(Command):
    """List files in a tree.
    """
    # TODO: Take a revision or remote path and list that tree instead.
    hidden = True
    takes_options = ['verbose', 'revision',
                     Option('non-recursive',
                            help='don\'t recurse into sub-directories'),
                     Option('from-root',
                            help='Print all paths from the root of the branch.'),
                     Option('unknown', help='Print unknown files'),
                     Option('versioned', help='Print versioned files'),
                     Option('ignored', help='Print ignored files'),

                     Option('null', help='Null separate the files'),
                    ]
    @display_command
    def run(self, revision=None, verbose=False, 
            non_recursive=False, from_root=False,
            unknown=False, versioned=False, ignored=False,
            null=False):

        if verbose and null:
            raise BzrCommandError('Cannot set both --verbose and --null')
        all = not (unknown or versioned or ignored)

        selection = {'I':ignored, '?':unknown, 'V':versioned}

        tree, relpath = WorkingTree.open_containing(u'.')
        if from_root:
            relpath = u''
        elif relpath:
            relpath += '/'
        if revision is not None:
            tree = tree.branch.repository.revision_tree(
                revision[0].in_history(tree.branch).rev_id)
        for fp, fc, kind, fid, entry in tree.list_files():
            if fp.startswith(relpath):
                fp = fp[len(relpath):]
                if non_recursive and '/' in fp:
                    continue
                if not all and not selection[fc]:
                    continue
                if verbose:
                    kindch = entry.kind_character()
                    print '%-8s %s%s' % (fc, fp, kindch)
                elif null:
                    sys.stdout.write(fp)
                    sys.stdout.write('\0')
                    sys.stdout.flush()
                else:
                    print fp


class cmd_unknowns(Command):
    """List unknown files."""
    @display_command
    def run(self):
        from bzrlib.osutils import quotefn
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
            print quotefn(f)


class cmd_ignore(Command):
    """Ignore a command or pattern.

    To remove patterns from the ignore list, edit the .bzrignore file.

    If the pattern contains a slash, it is compared to the whole path
    from the branch root.  Otherwise, it is compared to only the last
    component of the path.  To match a file only in the root directory,
    prepend './'.

    Ignore patterns are case-insensitive on case-insensitive systems.

    Note: wildcards must be quoted from the shell on Unix.

    examples:
        bzr ignore ./Makefile
        bzr ignore '*.class'
    """
    # TODO: Complain if the filename is absolute
    takes_args = ['name_pattern']
    
    def run(self, name_pattern):
        from bzrlib.atomicfile import AtomicFile
        import os.path

        tree, relpath = WorkingTree.open_containing(u'.')
        ifn = tree.abspath('.bzrignore')

        if os.path.exists(ifn):
            f = open(ifn, 'rt')
            try:
                igns = f.read().decode('utf-8')
            finally:
                f.close()
        else:
            igns = ''

        # TODO: If the file already uses crlf-style termination, maybe
        # we should use that for the newly added lines?

        if igns and igns[-1] != '\n':
            igns += '\n'
        igns += name_pattern + '\n'

        try:
            f = AtomicFile(ifn, 'wt')
            f.write(igns.encode('utf-8'))
            f.commit()
        finally:
            f.close()

        inv = tree.inventory
        if inv.path2id('.bzrignore'):
            mutter('.bzrignore is already versioned')
        else:
            mutter('need to make new .bzrignore file versioned')
            tree.add(['.bzrignore'])


class cmd_ignored(Command):
    """List ignored files and the patterns that matched them.

    See also: bzr ignore"""
    @display_command
    def run(self):
        tree = WorkingTree.open_containing(u'.')[0]
        for path, file_class, kind, file_id, entry in tree.list_files():
            if file_class != 'I':
                continue
            ## XXX: Slightly inefficient since this was already calculated
            pat = tree.is_ignored(path)
            print '%-50s %s' % (path, pat)


class cmd_lookup_revision(Command):
    """Lookup the revision-id from a revision-number

    example:
        bzr lookup-revision 33
    """
    hidden = True
    takes_args = ['revno']
    
    @display_command
    def run(self, revno):
        try:
            revno = int(revno)
        except ValueError:
            raise BzrCommandError("not a valid revision-number: %r" % revno)

        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)


class cmd_export(Command):
    """Export past revision to destination directory.

    If no revision is specified this exports the last committed revision.

    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
    given, try to find the format with the extension. If no extension
    is found exports to a directory (equivalent to --format=dir).

    Root may be the top directory for tar, tgz and tbz2 formats. If none
    is given, the top directory will be the root name of the file.

    Note: export of tree with non-ascii filenames to zip is not supported.

     Supported formats       Autodetected by extension
     -----------------       -------------------------
         dir                            -
         tar                          .tar
         tbz2                    .tar.bz2, .tbz2
         tgz                      .tar.gz, .tgz
         zip                          .zip
    """
    takes_args = ['dest']
    takes_options = ['revision', 'format', 'root']
    def run(self, dest, revision=None, format=None, root=None):
        import os.path
        from bzrlib.export import export
        tree = WorkingTree.open_containing(u'.')[0]
        b = tree.branch
        if revision is None:
            # should be tree.last_revision  FIXME
            rev_id = b.last_revision()
        else:
            if len(revision) != 1:
                raise BzrError('bzr export --revision takes exactly 1 argument')
            rev_id = revision[0].in_history(b).rev_id
        t = b.repository.revision_tree(rev_id)
        try:
            export(t, dest, format, root)
        except errors.NoSuchExportFormat, e:
            raise BzrCommandError('Unsupported export format: %s' % e.format)


class cmd_cat(Command):
    """Write a file's text from a previous revision."""

    takes_options = ['revision']
    takes_args = ['filename']

    @display_command
    def run(self, filename, revision=None):
        if revision is not None and len(revision) != 1:
            raise BzrCommandError("bzr cat --revision takes exactly one number")
        tree = None
        try:
            tree, relpath = WorkingTree.open_containing(filename)
            b = tree.branch
        except NotBranchError:
            pass

        if tree is None:
            b, relpath = Branch.open_containing(filename)
        if revision is None:
            revision_id = b.last_revision()
        else:
            revision_id = revision[0].in_history(b).rev_id
        b.print_file(relpath, revision_id)


class cmd_local_time_offset(Command):
    """Show the offset in seconds from GMT to local time."""
    hidden = True    
    @display_command
    def run(self):
        print bzrlib.osutils.local_time_offset()



class cmd_commit(Command):
    """Commit changes into a new revision.
    
    If no arguments are given, the entire tree is committed.

    If selected files are specified, only changes to those files are
    committed.  If a directory is specified then the directory and everything 
    within it is committed.

    A selected-file commit may fail in some cases where the committed
    tree would be invalid, such as trying to commit a file in a
    newly-added directory that is not itself committed.
    """
    # TODO: Run hooks on tree to-be-committed, and after commit.

    # TODO: Strict commit that fails if there are deleted files.
    #       (what does "deleted files" mean ??)

    # TODO: Give better message for -s, --summary, used by tla people

    # XXX: verbose currently does nothing

    takes_args = ['selected*']
    takes_options = ['message', 'verbose', 
                     Option('unchanged',
                            help='commit even if nothing has changed'),
                     Option('file', type=str, 
                            argname='msgfile',
                            help='file containing commit message'),
                     Option('strict',
                            help="refuse to commit if there are unknown "
                            "files in the working tree."),
                     ]
    aliases = ['ci', 'checkin']

    def run(self, message=None, file=None, verbose=True, selected_list=None,
            unchanged=False, strict=False):
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
                StrictCommitFailed)
        from bzrlib.msgeditor import edit_commit_message, \
                make_commit_message_template
        from tempfile import TemporaryFile
        import codecs

        # TODO: Need a blackbox test for invoking the external editor; may be
        # slightly problematic to run this cross-platform.

        # TODO: do more checks that the commit will succeed before 
        # spending the user's valuable time typing a commit message.
        #
        # TODO: if the commit *does* happen to fail, then save the commit 
        # message to a temporary file where it can be recovered
        tree, selected_list = tree_files(selected_list)
        if message is None and not file:
            template = make_commit_message_template(tree, selected_list)
            message = edit_commit_message(template)
            if message is None:
                raise BzrCommandError("please specify a commit message"
                                      " with either --message or --file")
        elif message and file:
            raise BzrCommandError("please specify either --message or --file")
        
        if file:
            import codecs
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()

        if message == "":
                raise BzrCommandError("empty commit message specified")
            
        try:
            tree.commit(message, specific_files=selected_list,
                        allow_pointless=unchanged, strict=strict)
        except PointlessCommit:
            # FIXME: This should really happen before the file is read in;
            # perhaps prepare the commit; get the message; then actually commit
            raise BzrCommandError("no changes to commit",
                                  ["use --unchanged to commit anyhow"])
        except ConflictsInTree:
            raise BzrCommandError("Conflicts detected in working tree.  "
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
        except StrictCommitFailed:
            raise BzrCommandError("Commit refused because there are unknown "
                                  "files in the working tree.")
        note('Committed revision %d.' % (tree.branch.revno(),))


class cmd_check(Command):
    """Validate consistency of branch history.

    This command checks various invariants about the branch storage to
    detect data corruption or bzr bugs.
    """
    takes_args = ['branch?']
    takes_options = ['verbose']

    def run(self, branch=None, verbose=False):
        from bzrlib.check import check
        if branch is None:
            tree = WorkingTree.open_containing()[0]
            branch = tree.branch
        else:
            branch = Branch.open(branch)
        check(branch, verbose)


class cmd_scan_cache(Command):
    hidden = True
    def run(self):
        from bzrlib.hashcache import HashCache

        c = HashCache(u'.')
        c.read()
        c.scan()
            
        print '%6d stats' % c.stat_count
        print '%6d in hashcache' % len(c._cache)
        print '%6d files removed from cache' % c.removed_count
        print '%6d hashes updated' % c.update_count
        print '%6d files changed too recently to cache' % c.danger_count

        if c.needs_write:
            c.write()


def get_format_type(typestring):
    """Parse and return a format specifier."""
    if typestring == "metadir":
        return bzrdir.BzrDirMetaFormat1()
    if typestring == "knit":
        format = bzrdir.BzrDirMetaFormat1()
        format.repository_format = bzrlib.repository.RepositoryFormatKnit1()
        return format
    msg = "No known bzr-dir format %s. Supported types are: metadir\n" %\
        (typestring)
    raise BzrCommandError(msg)


class cmd_upgrade(Command):
    """Upgrade branch storage to current format.

    The check command or bzr developers may sometimes advise you to run
    this command. When the default format has changed you may also be warned
    during other operations to upgrade.
    """
    takes_args = ['url?']
    takes_options = [
                     Option('format', 
                            help='Upgrade to a specific format rather than the'
                                 ' current default format. Currently this '
                                 ' option only accepts =metadir',
                            type=get_format_type),
                    ]


    def run(self, url='.', format=None):
        from bzrlib.upgrade import upgrade
        upgrade(url, format)


class cmd_whoami(Command):
    """Show bzr user id."""
    takes_options = ['email']
    
    @display_command
    def run(self, email=False):
        try:
            b = WorkingTree.open_containing(u'.')[0].branch
            config = bzrlib.config.BranchConfig(b)
        except NotBranchError:
            config = bzrlib.config.GlobalConfig()
        
        if email:
            print config.user_email()
        else:
            print config.username()


class cmd_nick(Command):
    """Print or set the branch nickname.  

    If unset, the tree root directory name is used as the nickname
    To print the current nickname, execute with no argument.  
    """
    takes_args = ['nickname?']
    def run(self, nickname=None):
        branch = Branch.open_containing(u'.')[0]
        if nickname is None:
            self.printme(branch)
        else:
            branch.nick = nickname

    @display_command
    def printme(self, branch):
        print branch.nick 


class cmd_selftest(Command):
    """Run internal test suite.
    
    This creates temporary test directories in the working directory,
    but not existing data is affected.  These directories are deleted
    if the tests pass, or left behind to help in debugging if they
    fail and --keep-output is specified.
    
    If arguments are given, they are regular expressions that say
    which tests should run.

    If the global option '--no-plugins' is given, plugins are not loaded
    before running the selftests.  This has two effects: features provided or
    modified by plugins will not be tested, and tests provided by plugins will
    not be run.

    examples:
        bzr selftest ignore
        bzr --no-plugins selftest -v
    """
    # TODO: --list should give a list of all available tests

    # NB: this is used from the class without creating an instance, which is
    # why it does not have a self parameter.
    def get_transport_type(typestring):
        """Parse and return a transport specifier."""
        if typestring == "sftp":
            from bzrlib.transport.sftp import SFTPAbsoluteServer
            return SFTPAbsoluteServer
        if typestring == "memory":
            from bzrlib.transport.memory import MemoryServer
            return MemoryServer
        msg = "No known transport type %s. Supported types are: sftp\n" %\
            (typestring)
        raise BzrCommandError(msg)

    hidden = True
    takes_args = ['testspecs*']
    takes_options = ['verbose',
                     Option('one', help='stop when one test fails'),
                     Option('keep-output', 
                            help='keep output directories when tests fail'),
                     Option('transport', 
                            help='Use a different transport by default '
                                 'throughout the test suite.',
                            type=get_transport_type),
                    ]

    def run(self, testspecs_list=None, verbose=False, one=False,
            keep_output=False, transport=None):
        import bzrlib.ui
        from bzrlib.tests import selftest
        # we don't want progress meters from the tests to go to the
        # real output; and we don't want log messages cluttering up
        # the real logs.
        save_ui = bzrlib.ui.ui_factory
        bzrlib.trace.info('running tests...')
        try:
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
            if testspecs_list is not None:
                pattern = '|'.join(testspecs_list)
            else:
                pattern = ".*"
            result = selftest(verbose=verbose, 
                              pattern=pattern,
                              stop_on_failure=one, 
                              keep_output=keep_output,
                              transport=transport)
            if result:
                bzrlib.trace.info('tests passed')
            else:
                bzrlib.trace.info('tests failed')
            return int(not result)
        finally:
            bzrlib.ui.ui_factory = save_ui


def _get_bzr_branch():
    """If bzr is run from a branch, return Branch or None"""
    import bzrlib.errors
    from bzrlib.branch import Branch
    from bzrlib.osutils import abspath
    from os.path import dirname
    
    try:
        branch = Branch.open(dirname(abspath(dirname(__file__))))
        return branch
    except bzrlib.errors.BzrError:
        return None
    

def show_version():
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
    # is bzrlib itself in a branch?
    branch = _get_bzr_branch()
    if branch:
        rh = branch.revision_history()
        revno = len(rh)
        print "  bzr checkout, revision %d" % (revno,)
        print "  nick: %s" % (branch.nick,)
        if rh:
            print "  revid: %s" % (rh[-1],)
    print bzrlib.__copyright__
    print "http://bazaar-ng.org/"
    print
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
    print "you may use, modify and redistribute it under the terms of the GNU"
    print "General Public License version 2 or later."


class cmd_version(Command):
    """Show version of bzr."""
    @display_command
    def run(self):
        show_version()

class cmd_rocks(Command):
    """Statement of optimism."""
    hidden = True
    @display_command
    def run(self):
        print "it sure does!"


class cmd_find_merge_base(Command):
    """Find and print a base revision for merging two branches.
    """
    # TODO: Options to specify revisions on either side, as if
    #       merging only part of the history.
    takes_args = ['branch', 'other']
    hidden = True
    
    @display_command
    def run(self, branch, other):
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
        
        branch1 = Branch.open_containing(branch)[0]
        branch2 = Branch.open_containing(other)[0]

        history_1 = branch1.revision_history()
        history_2 = branch2.revision_history()

        last1 = branch1.last_revision()
        last2 = branch2.last_revision()

        source = MultipleRevisionSources(branch1.repository, 
                                         branch2.repository)
        
        base_rev_id = common_ancestor(last1, last2, source)

        print 'merge base is revision %s' % base_rev_id
        
        return

        if base_revno is None:
            raise bzrlib.errors.UnrelatedBranches()

        print ' r%-6d in %s' % (base_revno, branch)

        other_revno = branch2.revision_id_to_revno(base_revid)
        
        print ' r%-6d in %s' % (other_revno, other)



class cmd_merge(Command):
    """Perform a three-way merge.
    
    The branch is the branch you will merge from.  By default, it will
    merge the latest revision.  If you specify a revision, that
    revision will be merged.  If you specify two revisions, the first
    will be used as a BASE, and the second one as OTHER.  Revision
    numbers are always relative to the specified branch.

    By default bzr will try to merge in all new work from the other
    branch, automatically determining an appropriate base.  If this
    fails, you may need to give an explicit base.
    
    Examples:

    To merge the latest revision from bzr.dev
    bzr merge ../bzr.dev

    To merge changes up to and including revision 82 from bzr.dev
    bzr merge -r 82 ../bzr.dev

    To merge the changes introduced by 82, without previous changes:
    bzr merge -r 81..82 ../bzr.dev
    
    merge refuses to run if there are any uncommitted changes, unless
    --force is given.
    """
    takes_args = ['branch?']
    takes_options = ['revision', 'force', 'merge-type', 'reprocess',
                     Option('show-base', help="Show base revision text in "
                            "conflicts")]

    def run(self, branch=None, revision=None, force=False, merge_type=None,
            show_base=False, reprocess=False):
        if merge_type is None:
            merge_type = Merge3Merger
        if branch is None:
            branch = WorkingTree.open_containing(u'.')[0].branch.get_parent()
            if branch is None:
                raise BzrCommandError("No merge location known or specified.")
            else:
                print "Using saved location: %s" % branch 
        if revision is None or len(revision) < 1:
            base = [None, None]
            other = [branch, -1]
        else:
            if len(revision) == 1:
                base = [None, None]
                other_branch = Branch.open_containing(branch)[0]
                revno = revision[0].in_history(other_branch).revno
                other = [branch, revno]
            else:
                assert len(revision) == 2
                if None in revision:
                    raise BzrCommandError(
                        "Merge doesn't permit that revision specifier.")
                b = Branch.open_containing(branch)[0]

                base = [branch, revision[0].in_history(b).revno]
                other = [branch, revision[1].in_history(b).revno]

        try:
            conflict_count = merge(other, base, check_clean=(not force),
                                   merge_type=merge_type, reprocess=reprocess,
                                   show_base=show_base, 
                                   pb=bzrlib.ui.ui_factory.progress_bar())
            if conflict_count != 0:
                return 1
            else:
                return 0
        except bzrlib.errors.AmbiguousBase, e:
            m = ("sorry, bzr can't determine the right merge base yet\n"
                 "candidates are:\n  "
                 + "\n  ".join(e.bases)
                 + "\n"
                 "please specify an explicit base with -r,\n"
                 "and (if you want) report this to the bzr developers\n")
            log_error(m)


class cmd_remerge(Command):
    """Redo a merge.
    """
    takes_args = ['file*']
    takes_options = ['merge-type', 'reprocess',
                     Option('show-base', help="Show base revision text in "
                            "conflicts")]

    def run(self, file_list=None, merge_type=None, show_base=False,
            reprocess=False):
        from bzrlib.merge import merge_inner, transform_tree
        if merge_type is None:
            merge_type = Merge3Merger
        tree, file_list = tree_files(file_list)
        tree.lock_write()
        try:
            pending_merges = tree.pending_merges() 
            if len(pending_merges) != 1:
                raise BzrCommandError("Sorry, remerge only works after normal"
                                      + " merges.  Not cherrypicking or"
                                      + "multi-merges.")
            repository = tree.branch.repository
            base_revision = common_ancestor(tree.branch.last_revision(), 
                                            pending_merges[0], repository)
            base_tree = repository.revision_tree(base_revision)
            other_tree = repository.revision_tree(pending_merges[0])
            interesting_ids = None
            if file_list is not None:
                interesting_ids = set()
                for filename in file_list:
                    file_id = tree.path2id(filename)
                    interesting_ids.add(file_id)
                    if tree.kind(file_id) != "directory":
                        continue
                    
                    for name, ie in tree.inventory.iter_entries(file_id):
                        interesting_ids.add(ie.file_id)
            transform_tree(tree, tree.basis_tree(), interesting_ids)
            if file_list is None:
                restore_files = list(tree.iter_conflicts())
            else:
                restore_files = file_list
            for filename in restore_files:
                try:
                    restore(tree.abspath(filename))
                except NotConflicted:
                    pass
            conflicts =  merge_inner(tree.branch, other_tree, base_tree, 
                                     interesting_ids = interesting_ids, 
                                     other_rev_id=pending_merges[0], 
                                     merge_type=merge_type, 
                                     show_base=show_base,
                                     reprocess=reprocess)
        finally:
            tree.unlock()
        if conflicts > 0:
            return 1
        else:
            return 0

class cmd_revert(Command):
    """Reverse all changes since the last commit.

    Only versioned files are affected.  Specify filenames to revert only 
    those files.  By default, any files that are changed will be backed up
    first.  Backup files have a '~' appended to their name.
    """
    takes_options = ['revision', 'no-backup']
    takes_args = ['file*']
    aliases = ['merge-revert']

    def run(self, revision=None, no_backup=False, file_list=None):
        from bzrlib.commands import parse_spec
        if file_list is not None:
            if len(file_list) == 0:
                raise BzrCommandError("No files specified")
        else:
            file_list = []
        
        tree, file_list = tree_files(file_list)
        if revision is None:
            # FIXME should be tree.last_revision
            rev_id = tree.branch.last_revision()
        elif len(revision) != 1:
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
        else:
            rev_id = revision[0].in_history(tree.branch).rev_id
        tree.revert(file_list, tree.branch.repository.revision_tree(rev_id),
                    not no_backup, bzrlib.ui.ui_factory.progress_bar())


class cmd_assert_fail(Command):
    """Test reporting of assertion failures"""
    hidden = True
    def run(self):
        assert False, "always fails"


class cmd_help(Command):
    """Show help on a command or other topic.

    For a list of all available commands, say 'bzr help commands'."""
    takes_options = [Option('long', 'show help on all commands')]
    takes_args = ['topic?']
    aliases = ['?']
    
    @display_command
    def run(self, topic=None, long=False):
        import help
        if topic is None and long:
            topic = "commands"
        help.help(topic)


class cmd_shell_complete(Command):
    """Show appropriate completions for context.

    For a list of all available commands, say 'bzr shell-complete'."""
    takes_args = ['context?']
    aliases = ['s-c']
    hidden = True
    
    @display_command
    def run(self, context=None):
        import shellcomplete
        shellcomplete.shellcomplete(context)


class cmd_fetch(Command):
    """Copy in history from another branch but don't merge it.

    This is an internal method used for pull and merge."""
    hidden = True
    takes_args = ['from_branch', 'to_branch']
    def run(self, from_branch, to_branch):
        from bzrlib.fetch import Fetcher
        from bzrlib.branch import Branch
        from_b = Branch.open(from_branch)
        to_b = Branch.open(to_branch)
        Fetcher(to_b, from_b)


class cmd_missing(Command):
    """Show unmerged/unpulled revisions between two branches.

    OTHER_BRANCH may be local or remote."""
    takes_args = ['other_branch?']
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
                     Option('mine-only', 
                            'Display changes in the local branch only'),
                     Option('theirs-only', 
                            'Display changes in the remote branch only'), 
                     'log-format',
                     'line',
                     'long', 
                     'short',
                     'show-ids',
                     'verbose'
                     ]

    def run(self, other_branch=None, reverse=False, mine_only=False,
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
            show_ids=False, verbose=False):
        from bzrlib.missing import find_unmerged, iter_log_data
        from bzrlib.log import log_formatter
        local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
        parent = local_branch.get_parent()
        if other_branch is None:
            other_branch = parent
            if other_branch is None:
                raise BzrCommandError("No missing location known or specified.")
            print "Using last location: " + local_branch.get_parent()
        remote_branch = bzrlib.branch.Branch.open(other_branch)
        local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
        if (log_format == None):
            default = bzrlib.config.BranchConfig(local_branch).log_format()
            log_format = get_log_format(long=long, short=short, line=line, default=default)
        lf = log_formatter(log_format, sys.stdout,
                           show_ids=show_ids,
                           show_timezone='original')
        if reverse is False:
            local_extra.reverse()
            remote_extra.reverse()
        if local_extra and not theirs_only:
            print "You have %d extra revision(s):" % len(local_extra)
            for data in iter_log_data(local_extra, local_branch.repository,
                                      verbose):
                lf.show(*data)
            printed_local = True
        else:
            printed_local = False
        if remote_extra and not mine_only:
            if printed_local is True:
                print "\n\n"
            print "You are missing %d revision(s):" % len(remote_extra)
            for data in iter_log_data(remote_extra, remote_branch.repository, 
                                      verbose):
                lf.show(*data)
        if not remote_extra and not local_extra:
            status_code = 0
            print "Branches are up to date."
        else:
            status_code = 1
        if parent is None and other_branch is not None:
            local_branch.set_parent(other_branch)
        return status_code


class cmd_plugins(Command):
    """List plugins"""
    hidden = True
    @display_command
    def run(self):
        import bzrlib.plugin
        from inspect import getdoc
        for name, plugin in bzrlib.plugin.all_plugins().items():
            if hasattr(plugin, '__path__'):
                print plugin.__path__[0]
            elif hasattr(plugin, '__file__'):
                print plugin.__file__
            else:
                print `plugin`
                
            d = getdoc(plugin)
            if d:
                print '\t', d.split('\n')[0]


class cmd_testament(Command):
    """Show testament (signing-form) of a revision."""
    takes_options = ['revision', 'long']
    takes_args = ['branch?']
    @display_command
    def run(self, branch=u'.', revision=None, long=False):
        from bzrlib.testament import Testament
        b = WorkingTree.open_containing(branch)[0].branch
        b.lock_read()
        try:
            if revision is None:
                rev_id = b.last_revision()
            else:
                rev_id = revision[0].in_history(b).rev_id
            t = Testament.from_revision(b.repository, rev_id)
            if long:
                sys.stdout.writelines(t.as_text_lines())
            else:
                sys.stdout.write(t.as_short_text())
        finally:
            b.unlock()


class cmd_annotate(Command):
    """Show the origin of each line in a file.

    This prints out the given file with an annotation on the left side
    indicating which revision, author and date introduced the change.

    If the origin is the same for a run of consecutive lines, it is 
    shown only at the top, unless the --all option is given.
    """
    # TODO: annotate directories; showing when each file was last changed
    # TODO: annotate a previous version of a file
    # TODO: if the working copy is modified, show annotations on that 
    #       with new uncommitted lines marked
    aliases = ['blame', 'praise']
    takes_args = ['filename']
    takes_options = [Option('all', help='show annotations on all lines'),
                     Option('long', help='show date in annotations'),
                     ]

    @display_command
    def run(self, filename, all=False, long=False):
        from bzrlib.annotate import annotate_file
        tree, relpath = WorkingTree.open_containing(filename)
        branch = tree.branch
        branch.lock_read()
        try:
            file_id = tree.inventory.path2id(relpath)
            tree = branch.repository.revision_tree(branch.last_revision())
            file_version = tree.inventory[file_id].revision
            annotate_file(branch, file_version, file_id, long, all, sys.stdout)
        finally:
            branch.unlock()


class cmd_re_sign(Command):
    """Create a digital signature for an existing revision."""
    # TODO be able to replace existing ones.

    hidden = True # is this right ?
    takes_args = ['revision_id*']
    takes_options = ['revision']
    
    def run(self, revision_id_list=None, revision=None):
        import bzrlib.config as config
        import bzrlib.gpg as gpg
        if revision_id_list is not None and revision is not None:
            raise BzrCommandError('You can only supply one of revision_id or --revision')
        if revision_id_list is None and revision is None:
            raise BzrCommandError('You must supply either --revision or a revision_id')
        b = WorkingTree.open_containing(u'.')[0].branch
        gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
        if revision_id_list is not None:
            for revision_id in revision_id_list:
                b.repository.sign_revision(revision_id, gpg_strategy)
        elif revision is not None:
            if len(revision) == 1:
                revno, rev_id = revision[0].in_history(b)
                b.repository.sign_revision(rev_id, gpg_strategy)
            elif len(revision) == 2:
                # are they both on rh- if so we can walk between them
                # might be nice to have a range helper for arbitrary
                # revision paths. hmm.
                from_revno, from_revid = revision[0].in_history(b)
                to_revno, to_revid = revision[1].in_history(b)
                if to_revid is None:
                    to_revno = b.revno()
                if from_revno is None or to_revno is None:
                    raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
                for revno in range(from_revno, to_revno + 1):
                    b.repository.sign_revision(b.get_rev_id(revno), 
                                               gpg_strategy)
            else:
                raise BzrCommandError('Please supply either one revision, or a range.')


class cmd_uncommit(bzrlib.commands.Command):
    """Remove the last committed revision.

    By supplying the --all flag, it will not only remove the entry 
    from revision_history, but also remove all of the entries in the
    stores.

    --verbose will print out what is being removed.
    --dry-run will go through all the motions, but not actually
    remove anything.
    
    In the future, uncommit will create a changeset, which can then
    be re-applied.

    TODO: jam 20060108 Add an option to allow uncommit to remove unreferenced
              information in 'branch-as-repostory' branches.
    TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
              information in shared branches as well.
    """
    takes_options = ['verbose', 'revision',
                    Option('dry-run', help='Don\'t actually make changes'),
                    Option('force', help='Say yes to all questions.')]
    takes_args = ['location?']
    aliases = []

    def run(self, location=None, 
            dry_run=False, verbose=False,
            revision=None, force=False):
        from bzrlib.branch import Branch
        from bzrlib.log import log_formatter
        import sys
        from bzrlib.uncommit import uncommit

        if location is None:
            location = u'.'
        control, relpath = bzrdir.BzrDir.open_containing(location)
        b = control.open_branch()
        try:
            tree = control.open_workingtree()
        except (errors.NoWorkingTree, errors.NotLocalUrl):
            tree = None

        if revision is None:
            revno = b.revno()
            rev_id = b.last_revision()
        else:
            revno, rev_id = revision[0].in_history(b)
        if rev_id is None:
            print 'No revisions to uncommit.'

        for r in range(revno, b.revno()+1):
            rev_id = b.get_rev_id(r)
            lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
            lf.show(r, b.repository.get_revision(rev_id), None)

        if dry_run:
            print 'Dry-run, pretending to remove the above revisions.'
            if not force:
                val = raw_input('Press <enter> to continue')
        else:
            print 'The above revision(s) will be removed.'
            if not force:
                val = raw_input('Are you sure [y/N]? ')
                if val.lower() not in ('y', 'yes'):
                    print 'Canceled'
                    return 0

        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
                revno=revno)


def merge(other_revision, base_revision,
          check_clean=True, ignore_zero=False,
          this_dir=None, backup_files=False, merge_type=Merge3Merger,
          file_list=None, show_base=False, reprocess=False, 
          pb=DummyProgress()):
    """Merge changes into a tree.

    base_revision
        list(path, revno) Base for three-way merge.  
        If [None, None] then a base will be automatically determined.
    other_revision
        list(path, revno) Other revision for three-way merge.
    this_dir
        Directory to merge changes into; '.' by default.
    check_clean
        If true, this_dir must have no uncommitted changes before the
        merge begins.
    ignore_zero - If true, suppress the "zero conflicts" message when 
        there are no conflicts; should be set when doing something we expect
        to complete perfectly.
    file_list - If supplied, merge only changes to selected files.

    All available ancestors of other_revision and base_revision are
    automatically pulled into the branch.

    The revno may be -1 to indicate the last revision on the branch, which is
    the typical case.

    This function is intended for use from the command line; programmatic
    clients might prefer to call merge.merge_inner(), which has less magic 
    behavior.
    """
    from bzrlib.merge import Merger
    if this_dir is None:
        this_dir = u'.'
    this_tree = WorkingTree.open_containing(this_dir)[0]
    if show_base and not merge_type is Merge3Merger:
        raise BzrCommandError("Show-base is not supported for this merge"
                              " type. %s" % merge_type)
    if reprocess and not merge_type is Merge3Merger:
        raise BzrCommandError("Reprocess is not supported for this merge"
                              " type. %s" % merge_type)
    if reprocess and show_base:
        raise BzrCommandError("Cannot reprocess and show base.")
    merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
    merger.check_basis(check_clean)
    merger.set_other(other_revision)
    merger.set_base(base_revision)
    if merger.base_rev_id == merger.other_rev_id:
        note('Nothing to do.')
        return 0
    merger.backup_files = backup_files
    merger.merge_type = merge_type 
    merger.set_interesting_files(file_list)
    merger.show_base = show_base 
    merger.reprocess = reprocess
    conflicts = merger.do_merge()
    merger.set_pending()
    return conflicts


# these get imported and then picked up by the scan for cmd_*
# TODO: Some more consistent way to split command definitions across files;
# we do need to load at least some information about them to know of 
# aliases.
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
from bzrlib.sign_my_commits import cmd_sign_my_commits