~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

[merge] test renames and other fixes (John)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005 by Canonical Ltd
 
2
 
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
 
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
 
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
# DO NOT change this to cStringIO - it results in control files 
 
18
# written as UCS4
 
19
# FIXIT! (Only deal with byte streams OR unicode at any one layer.)
 
20
# RBC 20051018
 
21
from StringIO import StringIO
 
22
import sys
 
23
import os
 
24
 
 
25
import bzrlib
 
26
from bzrlib import BZRDIR
 
27
from bzrlib.commands import Command, display_command
 
28
from bzrlib.branch import Branch
 
29
from bzrlib.revision import common_ancestor
 
30
import bzrlib.errors as errors
 
31
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError, 
 
32
                           NotBranchError, DivergedBranches, NotConflicted,
 
33
                           NoSuchFile, NoWorkingTree, FileInWrongBranch)
 
34
from bzrlib.option import Option
 
35
from bzrlib.revisionspec import RevisionSpec
 
36
import bzrlib.trace
 
37
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
 
38
from bzrlib.workingtree import WorkingTree
 
39
 
 
40
 
 
41
def tree_files(file_list, default_branch='.'):
 
42
    try:
 
43
        return internal_tree_files(file_list, default_branch)
 
44
    except FileInWrongBranch, e:
 
45
        raise BzrCommandError("%s is not in the same branch as %s" %
 
46
                             (e.path, file_list[0]))
 
47
 
 
48
def internal_tree_files(file_list, default_branch='.'):
 
49
    """\
 
50
    Return a branch and list of branch-relative paths.
 
51
    If supplied file_list is empty or None, the branch default will be used,
 
52
    and returned file_list will match the original.
 
53
    """
 
54
    if file_list is None or len(file_list) == 0:
 
55
        return WorkingTree.open_containing(default_branch)[0], file_list
 
56
    tree = WorkingTree.open_containing(file_list[0])[0]
 
57
    new_list = []
 
58
    for filename in file_list:
 
59
        try:
 
60
            new_list.append(tree.relpath(filename))
 
61
        except NotBranchError:
 
62
            raise FileInWrongBranch(tree.branch, filename)
 
63
    return tree, new_list
 
64
 
 
65
 
 
66
# TODO: Make sure no commands unconditionally use the working directory as a
 
67
# branch.  If a filename argument is used, the first of them should be used to
 
68
# specify the branch.  (Perhaps this can be factored out into some kind of
 
69
# Argument class, representing a file in a branch, where the first occurrence
 
70
# opens the branch?)
 
71
 
 
72
class cmd_status(Command):
 
73
    """Display status summary.
 
74
 
 
75
    This reports on versioned and unknown files, reporting them
 
76
    grouped by state.  Possible states are:
 
77
 
 
78
    added
 
79
        Versioned in the working copy but not in the previous revision.
 
80
 
 
81
    removed
 
82
        Versioned in the previous revision but removed or deleted
 
83
        in the working copy.
 
84
 
 
85
    renamed
 
86
        Path of this file changed from the previous revision;
 
87
        the text may also have changed.  This includes files whose
 
88
        parent directory was renamed.
 
89
 
 
90
    modified
 
91
        Text has changed since the previous revision.
 
92
 
 
93
    unchanged
 
94
        Nothing about this file has changed since the previous revision.
 
95
        Only shown with --all.
 
96
 
 
97
    unknown
 
98
        Not versioned and not matching an ignore pattern.
 
99
 
 
100
    To see ignored files use 'bzr ignored'.  For details in the
 
101
    changes to file texts, use 'bzr diff'.
 
102
 
 
103
    If no arguments are specified, the status of the entire working
 
104
    directory is shown.  Otherwise, only the status of the specified
 
105
    files or directories is reported.  If a directory is given, status
 
106
    is reported for everything inside that directory.
 
107
 
 
108
    If a revision argument is given, the status is calculated against
 
109
    that revision, or between two revisions if two are provided.
 
110
    """
 
111
    
 
112
    # TODO: --no-recurse, --recurse options
 
113
    
 
114
    takes_args = ['file*']
 
115
    takes_options = ['all', 'show-ids', 'revision']
 
116
    aliases = ['st', 'stat']
 
117
    
 
118
    @display_command
 
119
    def run(self, all=False, show_ids=False, file_list=None, revision=None):
 
120
        tree, file_list = tree_files(file_list)
 
121
            
 
122
        from bzrlib.status import show_status
 
123
        show_status(tree.branch, show_unchanged=all, show_ids=show_ids,
 
124
                    specific_files=file_list, revision=revision)
 
125
 
 
126
 
 
127
class cmd_cat_revision(Command):
 
128
    """Write out metadata for a revision.
 
129
    
 
130
    The revision to print can either be specified by a specific
 
131
    revision identifier, or you can use --revision.
 
132
    """
 
133
 
 
134
    hidden = True
 
135
    takes_args = ['revision_id?']
 
136
    takes_options = ['revision']
 
137
    
 
138
    @display_command
 
139
    def run(self, revision_id=None, revision=None):
 
140
 
 
141
        if revision_id is not None and revision is not None:
 
142
            raise BzrCommandError('You can only supply one of revision_id or --revision')
 
143
        if revision_id is None and revision is None:
 
144
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
145
        b = WorkingTree.open_containing('.')[0].branch
 
146
        if revision_id is not None:
 
147
            sys.stdout.write(b.get_revision_xml(revision_id))
 
148
        elif revision is not None:
 
149
            for rev in revision:
 
150
                if rev is None:
 
151
                    raise BzrCommandError('You cannot specify a NULL revision.')
 
152
                revno, rev_id = rev.in_history(b)
 
153
                sys.stdout.write(b.get_revision_xml(rev_id))
 
154
    
 
155
 
 
156
class cmd_revno(Command):
 
157
    """Show current revision number.
 
158
 
 
159
    This is equal to the number of revisions on this branch."""
 
160
    @display_command
 
161
    def run(self):
 
162
        print Branch.open_containing('.')[0].revno()
 
163
 
 
164
 
 
165
class cmd_revision_info(Command):
 
166
    """Show revision number and revision id for a given revision identifier.
 
167
    """
 
168
    hidden = True
 
169
    takes_args = ['revision_info*']
 
170
    takes_options = ['revision']
 
171
    @display_command
 
172
    def run(self, revision=None, revision_info_list=[]):
 
173
 
 
174
        revs = []
 
175
        if revision is not None:
 
176
            revs.extend(revision)
 
177
        if revision_info_list is not None:
 
178
            for rev in revision_info_list:
 
179
                revs.append(RevisionSpec(rev))
 
180
        if len(revs) == 0:
 
181
            raise BzrCommandError('You must supply a revision identifier')
 
182
 
 
183
        b = WorkingTree.open_containing('.')[0].branch
 
184
 
 
185
        for rev in revs:
 
186
            revinfo = rev.in_history(b)
 
187
            if revinfo.revno is None:
 
188
                print '     %s' % revinfo.rev_id
 
189
            else:
 
190
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
191
 
 
192
    
 
193
class cmd_add(Command):
 
194
    """Add specified files or directories.
 
195
 
 
196
    In non-recursive mode, all the named items are added, regardless
 
197
    of whether they were previously ignored.  A warning is given if
 
198
    any of the named files are already versioned.
 
199
 
 
200
    In recursive mode (the default), files are treated the same way
 
201
    but the behaviour for directories is different.  Directories that
 
202
    are already versioned do not give a warning.  All directories,
 
203
    whether already versioned or not, are searched for files or
 
204
    subdirectories that are neither versioned or ignored, and these
 
205
    are added.  This search proceeds recursively into versioned
 
206
    directories.  If no names are given '.' is assumed.
 
207
 
 
208
    Therefore simply saying 'bzr add' will version all files that
 
209
    are currently unknown.
 
210
 
 
211
    Adding a file whose parent directory is not versioned will
 
212
    implicitly add the parent, and so on up to the root. This means
 
213
    you should never need to explictly add a directory, they'll just
 
214
    get added when you add a file in the directory.
 
215
    """
 
216
    takes_args = ['file*']
 
217
    takes_options = ['no-recurse']
 
218
    
 
219
    def run(self, file_list, no_recurse=False):
 
220
        from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
 
221
        if is_quiet():
 
222
            reporter = add_reporter_null
 
223
        else:
 
224
            reporter = add_reporter_print
 
225
        smart_add(file_list, not no_recurse, reporter)
 
226
 
 
227
 
 
228
class cmd_mkdir(Command):
 
229
    """Create a new versioned directory.
 
230
 
 
231
    This is equivalent to creating the directory and then adding it.
 
232
    """
 
233
    takes_args = ['dir+']
 
234
 
 
235
    def run(self, dir_list):
 
236
        for d in dir_list:
 
237
            os.mkdir(d)
 
238
            wt, dd = WorkingTree.open_containing(d)
 
239
            wt.add([dd])
 
240
            print 'added', d
 
241
 
 
242
 
 
243
class cmd_relpath(Command):
 
244
    """Show path of a file relative to root"""
 
245
    takes_args = ['filename']
 
246
    hidden = True
 
247
    
 
248
    @display_command
 
249
    def run(self, filename):
 
250
        tree, relpath = WorkingTree.open_containing(filename)
 
251
        print relpath
 
252
 
 
253
 
 
254
class cmd_inventory(Command):
 
255
    """Show inventory of the current working copy or a revision.
 
256
 
 
257
    It is possible to limit the output to a particular entry
 
258
    type using the --kind option.  For example; --kind file.
 
259
    """
 
260
    takes_options = ['revision', 'show-ids', 'kind']
 
261
    
 
262
    @display_command
 
263
    def run(self, revision=None, show_ids=False, kind=None):
 
264
        if kind and kind not in ['file', 'directory', 'symlink']:
 
265
            raise BzrCommandError('invalid kind specified')
 
266
        tree = WorkingTree.open_containing('.')[0]
 
267
        if revision is None:
 
268
            inv = tree.read_working_inventory()
 
269
        else:
 
270
            if len(revision) > 1:
 
271
                raise BzrCommandError('bzr inventory --revision takes'
 
272
                    ' exactly one revision identifier')
 
273
            inv = tree.branch.get_revision_inventory(
 
274
                revision[0].in_history(tree.branch).rev_id)
 
275
 
 
276
        for path, entry in inv.entries():
 
277
            if kind and kind != entry.kind:
 
278
                continue
 
279
            if show_ids:
 
280
                print '%-50s %s' % (path, entry.file_id)
 
281
            else:
 
282
                print path
 
283
 
 
284
 
 
285
class cmd_move(Command):
 
286
    """Move files to a different directory.
 
287
 
 
288
    examples:
 
289
        bzr move *.txt doc
 
290
 
 
291
    The destination must be a versioned directory in the same branch.
 
292
    """
 
293
    takes_args = ['source$', 'dest']
 
294
    def run(self, source_list, dest):
 
295
        tree, source_list = tree_files(source_list)
 
296
        # TODO: glob expansion on windows?
 
297
        tree.move(source_list, tree.relpath(dest))
 
298
 
 
299
 
 
300
class cmd_rename(Command):
 
301
    """Change the name of an entry.
 
302
 
 
303
    examples:
 
304
      bzr rename frob.c frobber.c
 
305
      bzr rename src/frob.c lib/frob.c
 
306
 
 
307
    It is an error if the destination name exists.
 
308
 
 
309
    See also the 'move' command, which moves files into a different
 
310
    directory without changing their name.
 
311
    """
 
312
    # TODO: Some way to rename multiple files without invoking 
 
313
    # bzr for each one?"""
 
314
    takes_args = ['from_name', 'to_name']
 
315
    
 
316
    def run(self, from_name, to_name):
 
317
        tree, (from_name, to_name) = tree_files((from_name, to_name))
 
318
        tree.rename_one(from_name, to_name)
 
319
 
 
320
 
 
321
class cmd_mv(Command):
 
322
    """Move or rename a file.
 
323
 
 
324
    usage:
 
325
        bzr mv OLDNAME NEWNAME
 
326
        bzr mv SOURCE... DESTINATION
 
327
 
 
328
    If the last argument is a versioned directory, all the other names
 
329
    are moved into it.  Otherwise, there must be exactly two arguments
 
330
    and the file is changed to a new name, which must not already exist.
 
331
 
 
332
    Files cannot be moved between branches.
 
333
    """
 
334
    takes_args = ['names*']
 
335
    def run(self, names_list):
 
336
        if len(names_list) < 2:
 
337
            raise BzrCommandError("missing file argument")
 
338
        tree, rel_names = tree_files(names_list)
 
339
        
 
340
        if os.path.isdir(names_list[-1]):
 
341
            # move into existing directory
 
342
            for pair in tree.move(rel_names[:-1], rel_names[-1]):
 
343
                print "%s => %s" % pair
 
344
        else:
 
345
            if len(names_list) != 2:
 
346
                raise BzrCommandError('to mv multiple files the destination '
 
347
                                      'must be a versioned directory')
 
348
            tree.rename_one(rel_names[0], rel_names[1])
 
349
            print "%s => %s" % (rel_names[0], rel_names[1])
 
350
            
 
351
    
 
352
class cmd_pull(Command):
 
353
    """Pull any changes from another branch into the current one.
 
354
 
 
355
    If there is no default location set, the first pull will set it.  After
 
356
    that, you can omit the location to use the default.  To change the
 
357
    default, use --remember.
 
358
 
 
359
    This command only works on branches that have not diverged.  Branches are
 
360
    considered diverged if both branches have had commits without first
 
361
    pulling from the other.
 
362
 
 
363
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
364
    from one into the other.  Once one branch has merged, the other should
 
365
    be able to pull it again.
 
366
 
 
367
    If you want to forget your local changes and just update your branch to
 
368
    match the remote one, use --overwrite.
 
369
    """
 
370
    takes_options = ['remember', 'overwrite', 'verbose']
 
371
    takes_args = ['location?']
 
372
 
 
373
    def run(self, location=None, remember=False, overwrite=False, verbose=False):
 
374
        from bzrlib.merge import merge
 
375
        from shutil import rmtree
 
376
        import errno
 
377
        # FIXME: too much stuff is in the command class        
 
378
        tree_to = WorkingTree.open_containing('.')[0]
 
379
        stored_loc = tree_to.branch.get_parent()
 
380
        if location is None:
 
381
            if stored_loc is None:
 
382
                raise BzrCommandError("No pull location known or specified.")
 
383
            else:
 
384
                print "Using saved location: %s" % stored_loc
 
385
                location = stored_loc
 
386
        br_from = Branch.open(location)
 
387
        br_to = tree_to.branch
 
388
        try:
 
389
            old_rh = br_to.revision_history()
 
390
            count = tree_to.pull(br_from, overwrite)
 
391
        except DivergedBranches:
 
392
            # FIXME: Just make DivergedBranches display the right message
 
393
            # itself.
 
394
            raise BzrCommandError("These branches have diverged."
 
395
                                  "  Try merge.")
 
396
        if br_to.get_parent() is None or remember:
 
397
            br_to.set_parent(location)
 
398
        note('%d revision(s) pulled.', count)
 
399
        if verbose:
 
400
            new_rh = tree_to.branch.revision_history()
 
401
            if old_rh != new_rh:
 
402
                # Something changed
 
403
                from bzrlib.log import show_changed_revisions
 
404
                show_changed_revisions(tree_to.branch, old_rh, new_rh)
 
405
 
 
406
 
 
407
class cmd_push(Command):
 
408
    """Push this branch into another branch.
 
409
    
 
410
    The remote branch will not have its working tree populated because this
 
411
    is both expensive, and may not be supported on the remote file system.
 
412
    
 
413
    Some smart servers or protocols *may* put the working tree in place.
 
414
 
 
415
    If there is no default push location set, the first push will set it.
 
416
    After that, you can omit the location to use the default.  To change the
 
417
    default, use --remember.
 
418
 
 
419
    This command only works on branches that have not diverged.  Branches are
 
420
    considered diverged if the branch being pushed to is not an older version
 
421
    of this branch.
 
422
 
 
423
    If branches have diverged, you can use 'bzr push --overwrite' to replace
 
424
    the other branch completely.
 
425
    
 
426
    If you want to ensure you have the different changes in the other branch,
 
427
    do a merge (see bzr help merge) from the other branch, and commit that
 
428
    before doing a 'push --overwrite'.
 
429
    """
 
430
    takes_options = ['remember', 'overwrite', 
 
431
                     Option('create-prefix', 
 
432
                            help='Create the path leading up to the branch '
 
433
                                 'if it does not already exist')]
 
434
    takes_args = ['location?']
 
435
 
 
436
    def run(self, location=None, remember=False, overwrite=False,
 
437
            create_prefix=False, verbose=False):
 
438
        # FIXME: Way too big!  Put this into a function called from the
 
439
        # command.
 
440
        import errno
 
441
        from shutil import rmtree
 
442
        from bzrlib.transport import get_transport
 
443
        
 
444
        tree_from = WorkingTree.open_containing('.')[0]
 
445
        br_from = tree_from.branch
 
446
        stored_loc = tree_from.branch.get_push_location()
 
447
        if location is None:
 
448
            if stored_loc is None:
 
449
                raise BzrCommandError("No push location known or specified.")
 
450
            else:
 
451
                print "Using saved location: %s" % stored_loc
 
452
                location = stored_loc
 
453
        try:
 
454
            br_to = Branch.open(location)
 
455
        except NotBranchError:
 
456
            # create a branch.
 
457
            transport = get_transport(location).clone('..')
 
458
            if not create_prefix:
 
459
                try:
 
460
                    transport.mkdir(transport.relpath(location))
 
461
                except NoSuchFile:
 
462
                    raise BzrCommandError("Parent directory of %s "
 
463
                                          "does not exist." % location)
 
464
            else:
 
465
                current = transport.base
 
466
                needed = [(transport, transport.relpath(location))]
 
467
                while needed:
 
468
                    try:
 
469
                        transport, relpath = needed[-1]
 
470
                        transport.mkdir(relpath)
 
471
                        needed.pop()
 
472
                    except NoSuchFile:
 
473
                        new_transport = transport.clone('..')
 
474
                        needed.append((new_transport,
 
475
                                       new_transport.relpath(transport.base)))
 
476
                        if new_transport.base == transport.base:
 
477
                            raise BzrCommandError("Could not creeate "
 
478
                                                  "path prefix.")
 
479
            br_to = Branch.initialize(location)
 
480
        try:
 
481
            old_rh = br_to.revision_history()
 
482
            count = br_to.pull(br_from, overwrite)
 
483
        except DivergedBranches:
 
484
            raise BzrCommandError("These branches have diverged."
 
485
                                  "  Try a merge then push with overwrite.")
 
486
        if br_from.get_push_location() is None or remember:
 
487
            br_from.set_push_location(location)
 
488
        note('%d revision(s) pushed.' % (count,))
 
489
        if verbose:
 
490
            new_rh = br_to.revision_history()
 
491
            if old_rh != new_rh:
 
492
                # Something changed
 
493
                from bzrlib.log import show_changed_revisions
 
494
                show_changed_revisions(br_to, old_rh, new_rh)
 
495
 
 
496
 
 
497
class cmd_branch(Command):
 
498
    """Create a new copy of a branch.
 
499
 
 
500
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
501
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
502
 
 
503
    To retrieve the branch as of a particular revision, supply the --revision
 
504
    parameter, as in "branch foo/bar -r 5".
 
505
 
 
506
    --basis is to speed up branching from remote branches.  When specified, it
 
507
    copies all the file-contents, inventory and revision data from the basis
 
508
    branch before copying anything from the remote branch.
 
509
    """
 
510
    takes_args = ['from_location', 'to_location?']
 
511
    takes_options = ['revision', 'basis']
 
512
    aliases = ['get', 'clone']
 
513
 
 
514
    def run(self, from_location, to_location=None, revision=None, basis=None):
 
515
        from bzrlib.clone import copy_branch
 
516
        import errno
 
517
        from shutil import rmtree
 
518
        if revision is None:
 
519
            revision = [None]
 
520
        elif len(revision) > 1:
 
521
            raise BzrCommandError(
 
522
                'bzr branch --revision takes exactly 1 revision value')
 
523
        try:
 
524
            br_from = Branch.open(from_location)
 
525
        except OSError, e:
 
526
            if e.errno == errno.ENOENT:
 
527
                raise BzrCommandError('Source location "%s" does not'
 
528
                                      ' exist.' % to_location)
 
529
            else:
 
530
                raise
 
531
        br_from.lock_read()
 
532
        try:
 
533
            if basis is not None:
 
534
                basis_branch = WorkingTree.open_containing(basis)[0].branch
 
535
            else:
 
536
                basis_branch = None
 
537
            if len(revision) == 1 and revision[0] is not None:
 
538
                revision_id = revision[0].in_history(br_from)[1]
 
539
            else:
 
540
                revision_id = None
 
541
            if to_location is None:
 
542
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
543
                name = None
 
544
            else:
 
545
                name = os.path.basename(to_location) + '\n'
 
546
            try:
 
547
                os.mkdir(to_location)
 
548
            except OSError, e:
 
549
                if e.errno == errno.EEXIST:
 
550
                    raise BzrCommandError('Target directory "%s" already'
 
551
                                          ' exists.' % to_location)
 
552
                if e.errno == errno.ENOENT:
 
553
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
554
                                          to_location)
 
555
                else:
 
556
                    raise
 
557
            try:
 
558
                copy_branch(br_from, to_location, revision_id, basis_branch)
 
559
            except bzrlib.errors.NoSuchRevision:
 
560
                rmtree(to_location)
 
561
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
 
562
                raise BzrCommandError(msg)
 
563
            except bzrlib.errors.UnlistableBranch:
 
564
                rmtree(to_location)
 
565
                msg = "The branch %s cannot be used as a --basis"
 
566
                raise BzrCommandError(msg)
 
567
            branch = Branch.open(to_location)
 
568
            if name:
 
569
                name = StringIO(name)
 
570
                branch.put_controlfile('branch-name', name)
 
571
            note('Branched %d revision(s).' % branch.revno())
 
572
        finally:
 
573
            br_from.unlock()
 
574
 
 
575
 
 
576
class cmd_renames(Command):
 
577
    """Show list of renamed files.
 
578
    """
 
579
    # TODO: Option to show renames between two historical versions.
 
580
 
 
581
    # TODO: Only show renames under dir, rather than in the whole branch.
 
582
    takes_args = ['dir?']
 
583
 
 
584
    @display_command
 
585
    def run(self, dir='.'):
 
586
        tree = WorkingTree.open_containing(dir)[0]
 
587
        old_inv = tree.branch.basis_tree().inventory
 
588
        new_inv = tree.read_working_inventory()
 
589
 
 
590
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
591
        renames.sort()
 
592
        for old_name, new_name in renames:
 
593
            print "%s => %s" % (old_name, new_name)        
 
594
 
 
595
 
 
596
class cmd_info(Command):
 
597
    """Show statistical information about a branch."""
 
598
    takes_args = ['branch?']
 
599
    
 
600
    @display_command
 
601
    def run(self, branch=None):
 
602
        import info
 
603
        b = WorkingTree.open_containing(branch)[0].branch
 
604
        info.show_info(b)
 
605
 
 
606
 
 
607
class cmd_remove(Command):
 
608
    """Make a file unversioned.
 
609
 
 
610
    This makes bzr stop tracking changes to a versioned file.  It does
 
611
    not delete the working copy.
 
612
    """
 
613
    takes_args = ['file+']
 
614
    takes_options = ['verbose']
 
615
    aliases = ['rm']
 
616
    
 
617
    def run(self, file_list, verbose=False):
 
618
        tree, file_list = tree_files(file_list)
 
619
        tree.remove(file_list, verbose=verbose)
 
620
 
 
621
 
 
622
class cmd_file_id(Command):
 
623
    """Print file_id of a particular file or directory.
 
624
 
 
625
    The file_id is assigned when the file is first added and remains the
 
626
    same through all revisions where the file exists, even when it is
 
627
    moved or renamed.
 
628
    """
 
629
    hidden = True
 
630
    takes_args = ['filename']
 
631
    @display_command
 
632
    def run(self, filename):
 
633
        tree, relpath = WorkingTree.open_containing(filename)
 
634
        i = tree.inventory.path2id(relpath)
 
635
        if i == None:
 
636
            raise BzrError("%r is not a versioned file" % filename)
 
637
        else:
 
638
            print i
 
639
 
 
640
 
 
641
class cmd_file_path(Command):
 
642
    """Print path of file_ids to a file or directory.
 
643
 
 
644
    This prints one line for each directory down to the target,
 
645
    starting at the branch root."""
 
646
    hidden = True
 
647
    takes_args = ['filename']
 
648
    @display_command
 
649
    def run(self, filename):
 
650
        tree, relpath = WorkingTree.open_containing(filename)
 
651
        inv = tree.inventory
 
652
        fid = inv.path2id(relpath)
 
653
        if fid == None:
 
654
            raise BzrError("%r is not a versioned file" % filename)
 
655
        for fip in inv.get_idpath(fid):
 
656
            print fip
 
657
 
 
658
 
 
659
class cmd_revision_history(Command):
 
660
    """Display list of revision ids on this branch."""
 
661
    hidden = True
 
662
    @display_command
 
663
    def run(self):
 
664
        branch = WorkingTree.open_containing('.')[0].branch
 
665
        for patchid in branch.revision_history():
 
666
            print patchid
 
667
 
 
668
 
 
669
class cmd_ancestry(Command):
 
670
    """List all revisions merged into this branch."""
 
671
    hidden = True
 
672
    @display_command
 
673
    def run(self):
 
674
        tree = WorkingTree.open_containing('.')[0]
 
675
        b = tree.branch
 
676
        # FIXME. should be tree.last_revision
 
677
        for revision_id in b.get_ancestry(b.last_revision()):
 
678
            print revision_id
 
679
 
 
680
 
 
681
class cmd_init(Command):
 
682
    """Make a directory into a versioned branch.
 
683
 
 
684
    Use this to create an empty branch, or before importing an
 
685
    existing project.
 
686
 
 
687
    Recipe for importing a tree of files:
 
688
        cd ~/project
 
689
        bzr init
 
690
        bzr add .
 
691
        bzr status
 
692
        bzr commit -m 'imported project'
 
693
    """
 
694
    takes_args = ['location?']
 
695
    def run(self, location=None):
 
696
        from bzrlib.branch import Branch
 
697
        if location is None:
 
698
            location = '.'
 
699
        else:
 
700
            # The path has to exist to initialize a
 
701
            # branch inside of it.
 
702
            # Just using os.mkdir, since I don't
 
703
            # believe that we want to create a bunch of
 
704
            # locations if the user supplies an extended path
 
705
            if not os.path.exists(location):
 
706
                os.mkdir(location)
 
707
        Branch.initialize(location)
 
708
 
 
709
 
 
710
class cmd_diff(Command):
 
711
    """Show differences in working tree.
 
712
    
 
713
    If files are listed, only the changes in those files are listed.
 
714
    Otherwise, all changes for the tree are listed.
 
715
 
 
716
    examples:
 
717
        bzr diff
 
718
        bzr diff -r1
 
719
        bzr diff -r1..2
 
720
    """
 
721
    # TODO: Allow diff across branches.
 
722
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
 
723
    #       or a graphical diff.
 
724
 
 
725
    # TODO: Python difflib is not exactly the same as unidiff; should
 
726
    #       either fix it up or prefer to use an external diff.
 
727
 
 
728
    # TODO: If a directory is given, diff everything under that.
 
729
 
 
730
    # TODO: Selected-file diff is inefficient and doesn't show you
 
731
    #       deleted files.
 
732
 
 
733
    # TODO: This probably handles non-Unix newlines poorly.
 
734
    
 
735
    takes_args = ['file*']
 
736
    takes_options = ['revision', 'diff-options']
 
737
    aliases = ['di', 'dif']
 
738
 
 
739
    @display_command
 
740
    def run(self, revision=None, file_list=None, diff_options=None):
 
741
        from bzrlib.diff import show_diff
 
742
        try:
 
743
            tree, file_list = internal_tree_files(file_list)
 
744
            b = None
 
745
            b2 = None
 
746
        except FileInWrongBranch:
 
747
            if len(file_list) != 2:
 
748
                raise BzrCommandError("Files are in different branches")
 
749
 
 
750
            b, file1 = Branch.open_containing(file_list[0])
 
751
            b2, file2 = Branch.open_containing(file_list[1])
 
752
            if file1 != "" or file2 != "":
 
753
                # FIXME diff those two files. rbc 20051123
 
754
                raise BzrCommandError("Files are in different branches")
 
755
            file_list = None
 
756
        if revision is not None:
 
757
            if b2 is not None:
 
758
                raise BzrCommandError("Can't specify -r with two branches")
 
759
            if len(revision) == 1:
 
760
                return show_diff(tree.branch, revision[0], specific_files=file_list,
 
761
                                 external_diff_options=diff_options)
 
762
            elif len(revision) == 2:
 
763
                return show_diff(tree.branch, revision[0], specific_files=file_list,
 
764
                                 external_diff_options=diff_options,
 
765
                                 revision2=revision[1])
 
766
            else:
 
767
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
768
        else:
 
769
            if b is not None:
 
770
                return show_diff(b, None, specific_files=file_list,
 
771
                                 external_diff_options=diff_options, b2=b2)
 
772
            else:
 
773
                return show_diff(tree.branch, None, specific_files=file_list,
 
774
                                 external_diff_options=diff_options)
 
775
 
 
776
 
 
777
class cmd_deleted(Command):
 
778
    """List files deleted in the working tree.
 
779
    """
 
780
    # TODO: Show files deleted since a previous revision, or
 
781
    # between two revisions.
 
782
    # TODO: Much more efficient way to do this: read in new
 
783
    # directories with readdir, rather than stating each one.  Same
 
784
    # level of effort but possibly much less IO.  (Or possibly not,
 
785
    # if the directories are very large...)
 
786
    @display_command
 
787
    def run(self, show_ids=False):
 
788
        tree = WorkingTree.open_containing('.')[0]
 
789
        old = tree.branch.basis_tree()
 
790
        for path, ie in old.inventory.iter_entries():
 
791
            if not tree.has_id(ie.file_id):
 
792
                if show_ids:
 
793
                    print '%-50s %s' % (path, ie.file_id)
 
794
                else:
 
795
                    print path
 
796
 
 
797
 
 
798
class cmd_modified(Command):
 
799
    """List files modified in working tree."""
 
800
    hidden = True
 
801
    @display_command
 
802
    def run(self):
 
803
        from bzrlib.delta import compare_trees
 
804
 
 
805
        tree = WorkingTree.open_containing('.')[0]
 
806
        td = compare_trees(tree.branch.basis_tree(), tree)
 
807
 
 
808
        for path, id, kind, text_modified, meta_modified in td.modified:
 
809
            print path
 
810
 
 
811
 
 
812
 
 
813
class cmd_added(Command):
 
814
    """List files added in working tree."""
 
815
    hidden = True
 
816
    @display_command
 
817
    def run(self):
 
818
        wt = WorkingTree.open_containing('.')[0]
 
819
        basis_inv = wt.branch.basis_tree().inventory
 
820
        inv = wt.inventory
 
821
        for file_id in inv:
 
822
            if file_id in basis_inv:
 
823
                continue
 
824
            path = inv.id2path(file_id)
 
825
            if not os.access(b.abspath(path), os.F_OK):
 
826
                continue
 
827
            print path
 
828
                
 
829
        
 
830
 
 
831
class cmd_root(Command):
 
832
    """Show the tree root directory.
 
833
 
 
834
    The root is the nearest enclosing directory with a .bzr control
 
835
    directory."""
 
836
    takes_args = ['filename?']
 
837
    @display_command
 
838
    def run(self, filename=None):
 
839
        """Print the branch root."""
 
840
        tree = WorkingTree.open_containing(filename)[0]
 
841
        print tree.basedir
 
842
 
 
843
 
 
844
class cmd_log(Command):
 
845
    """Show log of this branch.
 
846
 
 
847
    To request a range of logs, you can use the command -r begin..end
 
848
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
849
    also valid.
 
850
    """
 
851
 
 
852
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
853
 
 
854
    takes_args = ['filename?']
 
855
    takes_options = [Option('forward', 
 
856
                            help='show from oldest to newest'),
 
857
                     'timezone', 'verbose', 
 
858
                     'show-ids', 'revision',
 
859
                     Option('line', help='format with one line per revision'),
 
860
                     'long', 
 
861
                     Option('message',
 
862
                            help='show revisions whose message matches this regexp',
 
863
                            type=str),
 
864
                     Option('short', help='use moderately short format'),
 
865
                     ]
 
866
    @display_command
 
867
    def run(self, filename=None, timezone='original',
 
868
            verbose=False,
 
869
            show_ids=False,
 
870
            forward=False,
 
871
            revision=None,
 
872
            message=None,
 
873
            long=False,
 
874
            short=False,
 
875
            line=False):
 
876
        from bzrlib.log import log_formatter, show_log
 
877
        import codecs
 
878
        assert message is None or isinstance(message, basestring), \
 
879
            "invalid message argument %r" % message
 
880
        direction = (forward and 'forward') or 'reverse'
 
881
        
 
882
        if filename:
 
883
            # might be a tree:
 
884
            tree = None
 
885
            try:
 
886
                tree, fp = WorkingTree.open_containing(filename)
 
887
                b = tree.branch
 
888
                if fp != '':
 
889
                    inv = tree.read_working_inventory()
 
890
            except NotBranchError:
 
891
                pass
 
892
            if tree is None:
 
893
                b, fp = Branch.open_containing(filename)
 
894
                if fp != '':
 
895
                    inv = b.get_inventory(b.last_revision())
 
896
            if fp != '':
 
897
                file_id = inv.path2id(fp)
 
898
            else:
 
899
                file_id = None  # points to branch root
 
900
        else:
 
901
            tree, relpath = WorkingTree.open_containing('.')
 
902
            b = tree.branch
 
903
            file_id = None
 
904
 
 
905
        if revision is None:
 
906
            rev1 = None
 
907
            rev2 = None
 
908
        elif len(revision) == 1:
 
909
            rev1 = rev2 = revision[0].in_history(b).revno
 
910
        elif len(revision) == 2:
 
911
            rev1 = revision[0].in_history(b).revno
 
912
            rev2 = revision[1].in_history(b).revno
 
913
        else:
 
914
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
915
 
 
916
        # By this point, the revision numbers are converted to the +ve
 
917
        # form if they were supplied in the -ve form, so we can do
 
918
        # this comparison in relative safety
 
919
        if rev1 > rev2:
 
920
            (rev2, rev1) = (rev1, rev2)
 
921
 
 
922
        mutter('encoding log as %r', bzrlib.user_encoding)
 
923
 
 
924
        # use 'replace' so that we don't abort if trying to write out
 
925
        # in e.g. the default C locale.
 
926
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
927
 
 
928
        log_format = 'long'
 
929
        if short:
 
930
            log_format = 'short'
 
931
        if line:
 
932
            log_format = 'line'
 
933
        lf = log_formatter(log_format,
 
934
                           show_ids=show_ids,
 
935
                           to_file=outf,
 
936
                           show_timezone=timezone)
 
937
 
 
938
        show_log(b,
 
939
                 lf,
 
940
                 file_id,
 
941
                 verbose=verbose,
 
942
                 direction=direction,
 
943
                 start_revision=rev1,
 
944
                 end_revision=rev2,
 
945
                 search=message)
 
946
 
 
947
 
 
948
 
 
949
class cmd_touching_revisions(Command):
 
950
    """Return revision-ids which affected a particular file.
 
951
 
 
952
    A more user-friendly interface is "bzr log FILE"."""
 
953
    hidden = True
 
954
    takes_args = ["filename"]
 
955
    @display_command
 
956
    def run(self, filename):
 
957
        tree, relpath = WorkingTree.open_containing(filename)
 
958
        b = tree.branch
 
959
        inv = tree.read_working_inventory()
 
960
        file_id = inv.path2id(relpath)
 
961
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
962
            print "%6d %s" % (revno, what)
 
963
 
 
964
 
 
965
class cmd_ls(Command):
 
966
    """List files in a tree.
 
967
    """
 
968
    # TODO: Take a revision or remote path and list that tree instead.
 
969
    hidden = True
 
970
    takes_options = ['verbose', 'revision',
 
971
                     Option('non-recursive',
 
972
                            help='don\'t recurse into sub-directories'),
 
973
                     Option('from-root',
 
974
                            help='Print all paths from the root of the branch.'),
 
975
                     Option('unknown', help='Print unknown files'),
 
976
                     Option('versioned', help='Print versioned files'),
 
977
                     Option('ignored', help='Print ignored files'),
 
978
 
 
979
                     Option('null', help='Null separate the files'),
 
980
                    ]
 
981
    @display_command
 
982
    def run(self, revision=None, verbose=False, 
 
983
            non_recursive=False, from_root=False,
 
984
            unknown=False, versioned=False, ignored=False,
 
985
            null=False):
 
986
 
 
987
        if verbose and null:
 
988
            raise BzrCommandError('Cannot set both --verbose and --null')
 
989
        all = not (unknown or versioned or ignored)
 
990
 
 
991
        selection = {'I':ignored, '?':unknown, 'V':versioned}
 
992
 
 
993
        tree, relpath = WorkingTree.open_containing('.')
 
994
        if from_root:
 
995
            relpath = ''
 
996
        elif relpath:
 
997
            relpath += '/'
 
998
        if revision is not None:
 
999
            tree = tree.branch.revision_tree(
 
1000
                revision[0].in_history(tree.branch).rev_id)
 
1001
        for fp, fc, kind, fid, entry in tree.list_files():
 
1002
            if fp.startswith(relpath):
 
1003
                fp = fp[len(relpath):]
 
1004
                if non_recursive and '/' in fp:
 
1005
                    continue
 
1006
                if not all and not selection[fc]:
 
1007
                    continue
 
1008
                if verbose:
 
1009
                    kindch = entry.kind_character()
 
1010
                    print '%-8s %s%s' % (fc, fp, kindch)
 
1011
                elif null:
 
1012
                    sys.stdout.write(fp)
 
1013
                    sys.stdout.write('\0')
 
1014
                    sys.stdout.flush()
 
1015
                else:
 
1016
                    print fp
 
1017
 
 
1018
 
 
1019
class cmd_unknowns(Command):
 
1020
    """List unknown files."""
 
1021
    @display_command
 
1022
    def run(self):
 
1023
        from bzrlib.osutils import quotefn
 
1024
        for f in WorkingTree.open_containing('.')[0].unknowns():
 
1025
            print quotefn(f)
 
1026
 
 
1027
 
 
1028
class cmd_ignore(Command):
 
1029
    """Ignore a command or pattern.
 
1030
 
 
1031
    To remove patterns from the ignore list, edit the .bzrignore file.
 
1032
 
 
1033
    If the pattern contains a slash, it is compared to the whole path
 
1034
    from the branch root.  Otherwise, it is compared to only the last
 
1035
    component of the path.  To match a file only in the root directory,
 
1036
    prepend './'.
 
1037
 
 
1038
    Ignore patterns are case-insensitive on case-insensitive systems.
 
1039
 
 
1040
    Note: wildcards must be quoted from the shell on Unix.
 
1041
 
 
1042
    examples:
 
1043
        bzr ignore ./Makefile
 
1044
        bzr ignore '*.class'
 
1045
    """
 
1046
    # TODO: Complain if the filename is absolute
 
1047
    takes_args = ['name_pattern']
 
1048
    
 
1049
    def run(self, name_pattern):
 
1050
        from bzrlib.atomicfile import AtomicFile
 
1051
        import os.path
 
1052
 
 
1053
        tree, relpath = WorkingTree.open_containing('.')
 
1054
        ifn = tree.abspath('.bzrignore')
 
1055
 
 
1056
        if os.path.exists(ifn):
 
1057
            f = open(ifn, 'rt')
 
1058
            try:
 
1059
                igns = f.read().decode('utf-8')
 
1060
            finally:
 
1061
                f.close()
 
1062
        else:
 
1063
            igns = ''
 
1064
 
 
1065
        # TODO: If the file already uses crlf-style termination, maybe
 
1066
        # we should use that for the newly added lines?
 
1067
 
 
1068
        if igns and igns[-1] != '\n':
 
1069
            igns += '\n'
 
1070
        igns += name_pattern + '\n'
 
1071
 
 
1072
        try:
 
1073
            f = AtomicFile(ifn, 'wt')
 
1074
            f.write(igns.encode('utf-8'))
 
1075
            f.commit()
 
1076
        finally:
 
1077
            f.close()
 
1078
 
 
1079
        inv = tree.inventory
 
1080
        if inv.path2id('.bzrignore'):
 
1081
            mutter('.bzrignore is already versioned')
 
1082
        else:
 
1083
            mutter('need to make new .bzrignore file versioned')
 
1084
            tree.add(['.bzrignore'])
 
1085
 
 
1086
 
 
1087
class cmd_ignored(Command):
 
1088
    """List ignored files and the patterns that matched them.
 
1089
 
 
1090
    See also: bzr ignore"""
 
1091
    @display_command
 
1092
    def run(self):
 
1093
        tree = WorkingTree.open_containing('.')[0]
 
1094
        for path, file_class, kind, file_id, entry in tree.list_files():
 
1095
            if file_class != 'I':
 
1096
                continue
 
1097
            ## XXX: Slightly inefficient since this was already calculated
 
1098
            pat = tree.is_ignored(path)
 
1099
            print '%-50s %s' % (path, pat)
 
1100
 
 
1101
 
 
1102
class cmd_lookup_revision(Command):
 
1103
    """Lookup the revision-id from a revision-number
 
1104
 
 
1105
    example:
 
1106
        bzr lookup-revision 33
 
1107
    """
 
1108
    hidden = True
 
1109
    takes_args = ['revno']
 
1110
    
 
1111
    @display_command
 
1112
    def run(self, revno):
 
1113
        try:
 
1114
            revno = int(revno)
 
1115
        except ValueError:
 
1116
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
1117
 
 
1118
        print WorkingTree.open_containing('.')[0].branch.get_rev_id(revno)
 
1119
 
 
1120
 
 
1121
class cmd_export(Command):
 
1122
    """Export past revision to destination directory.
 
1123
 
 
1124
    If no revision is specified this exports the last committed revision.
 
1125
 
 
1126
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1127
    given, try to find the format with the extension. If no extension
 
1128
    is found exports to a directory (equivalent to --format=dir).
 
1129
 
 
1130
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1131
    is given, the top directory will be the root name of the file.
 
1132
 
 
1133
    Note: export of tree with non-ascii filenames to zip is not supported.
 
1134
 
 
1135
    Supported formats       Autodetected by extension
 
1136
    -----------------       -------------------------
 
1137
         dir                            -
 
1138
         tar                          .tar
 
1139
         tbz2                    .tar.bz2, .tbz2
 
1140
         tgz                      .tar.gz, .tgz
 
1141
         zip                          .zip
 
1142
    """
 
1143
    takes_args = ['dest']
 
1144
    takes_options = ['revision', 'format', 'root']
 
1145
    def run(self, dest, revision=None, format=None, root=None):
 
1146
        import os.path
 
1147
        from bzrlib.export import export
 
1148
        tree = WorkingTree.open_containing('.')[0]
 
1149
        b = tree.branch
 
1150
        if revision is None:
 
1151
            # should be tree.last_revision  FIXME
 
1152
            rev_id = b.last_revision()
 
1153
        else:
 
1154
            if len(revision) != 1:
 
1155
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
1156
            rev_id = revision[0].in_history(b).rev_id
 
1157
        t = b.revision_tree(rev_id)
 
1158
        try:
 
1159
            export(t, dest, format, root)
 
1160
        except errors.NoSuchExportFormat, e:
 
1161
            raise BzrCommandError('Unsupported export format: %s' % e.format)
 
1162
 
 
1163
 
 
1164
class cmd_cat(Command):
 
1165
    """Write a file's text from a previous revision."""
 
1166
 
 
1167
    takes_options = ['revision']
 
1168
    takes_args = ['filename']
 
1169
 
 
1170
    @display_command
 
1171
    def run(self, filename, revision=None):
 
1172
        if revision is None:
 
1173
            raise BzrCommandError("bzr cat requires a revision number")
 
1174
        elif len(revision) != 1:
 
1175
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
1176
        tree = None
 
1177
        try:
 
1178
            tree, relpath = WorkingTree.open_containing(filename)
 
1179
            b = tree.branch
 
1180
        except NotBranchError:
 
1181
            pass
 
1182
        if tree is None:
 
1183
            b, relpath = Branch.open_containing(filename)
 
1184
        b.print_file(relpath, revision[0].in_history(b).revno)
 
1185
 
 
1186
 
 
1187
class cmd_local_time_offset(Command):
 
1188
    """Show the offset in seconds from GMT to local time."""
 
1189
    hidden = True    
 
1190
    @display_command
 
1191
    def run(self):
 
1192
        print bzrlib.osutils.local_time_offset()
 
1193
 
 
1194
 
 
1195
 
 
1196
class cmd_commit(Command):
 
1197
    """Commit changes into a new revision.
 
1198
    
 
1199
    If no arguments are given, the entire tree is committed.
 
1200
 
 
1201
    If selected files are specified, only changes to those files are
 
1202
    committed.  If a directory is specified then the directory and everything 
 
1203
    within it is committed.
 
1204
 
 
1205
    A selected-file commit may fail in some cases where the committed
 
1206
    tree would be invalid, such as trying to commit a file in a
 
1207
    newly-added directory that is not itself committed.
 
1208
    """
 
1209
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
1210
 
 
1211
    # TODO: Strict commit that fails if there are deleted files.
 
1212
    #       (what does "deleted files" mean ??)
 
1213
 
 
1214
    # TODO: Give better message for -s, --summary, used by tla people
 
1215
 
 
1216
    # XXX: verbose currently does nothing
 
1217
 
 
1218
    takes_args = ['selected*']
 
1219
    takes_options = ['message', 'verbose', 
 
1220
                     Option('unchanged',
 
1221
                            help='commit even if nothing has changed'),
 
1222
                     Option('file', type=str, 
 
1223
                            argname='msgfile',
 
1224
                            help='file containing commit message'),
 
1225
                     Option('strict',
 
1226
                            help="refuse to commit if there are unknown "
 
1227
                            "files in the working tree."),
 
1228
                     ]
 
1229
    aliases = ['ci', 'checkin']
 
1230
 
 
1231
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1232
            unchanged=False, strict=False):
 
1233
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
 
1234
                StrictCommitFailed)
 
1235
        from bzrlib.msgeditor import edit_commit_message
 
1236
        from bzrlib.status import show_status
 
1237
        from cStringIO import StringIO
 
1238
 
 
1239
        tree, selected_list = tree_files(selected_list)
 
1240
        if message is None and not file:
 
1241
            catcher = StringIO()
 
1242
            show_status(tree.branch, specific_files=selected_list,
 
1243
                        to_file=catcher)
 
1244
            message = edit_commit_message(catcher.getvalue())
 
1245
 
 
1246
            if message is None:
 
1247
                raise BzrCommandError("please specify a commit message"
 
1248
                                      " with either --message or --file")
 
1249
        elif message and file:
 
1250
            raise BzrCommandError("please specify either --message or --file")
 
1251
        
 
1252
        if file:
 
1253
            import codecs
 
1254
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
1255
 
 
1256
        if message == "":
 
1257
                raise BzrCommandError("empty commit message specified")
 
1258
            
 
1259
        try:
 
1260
            tree.commit(message, specific_files=selected_list,
 
1261
                        allow_pointless=unchanged, strict=strict)
 
1262
        except PointlessCommit:
 
1263
            # FIXME: This should really happen before the file is read in;
 
1264
            # perhaps prepare the commit; get the message; then actually commit
 
1265
            raise BzrCommandError("no changes to commit",
 
1266
                                  ["use --unchanged to commit anyhow"])
 
1267
        except ConflictsInTree:
 
1268
            raise BzrCommandError("Conflicts detected in working tree.  "
 
1269
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
 
1270
        except StrictCommitFailed:
 
1271
            raise BzrCommandError("Commit refused because there are unknown "
 
1272
                                  "files in the working tree.")
 
1273
        note('Committed revision %d.' % (tree.branch.revno(),))
 
1274
        
 
1275
 
 
1276
class cmd_check(Command):
 
1277
    """Validate consistency of branch history.
 
1278
 
 
1279
    This command checks various invariants about the branch storage to
 
1280
    detect data corruption or bzr bugs.
 
1281
    """
 
1282
    takes_args = ['dir?']
 
1283
    takes_options = ['verbose']
 
1284
 
 
1285
    def run(self, dir='.', verbose=False):
 
1286
        from bzrlib.check import check
 
1287
        check(WorkingTree.open_containing(dir)[0].branch, verbose)
 
1288
 
 
1289
 
 
1290
class cmd_scan_cache(Command):
 
1291
    hidden = True
 
1292
    def run(self):
 
1293
        from bzrlib.hashcache import HashCache
 
1294
 
 
1295
        c = HashCache('.')
 
1296
        c.read()
 
1297
        c.scan()
 
1298
            
 
1299
        print '%6d stats' % c.stat_count
 
1300
        print '%6d in hashcache' % len(c._cache)
 
1301
        print '%6d files removed from cache' % c.removed_count
 
1302
        print '%6d hashes updated' % c.update_count
 
1303
        print '%6d files changed too recently to cache' % c.danger_count
 
1304
 
 
1305
        if c.needs_write:
 
1306
            c.write()
 
1307
            
 
1308
 
 
1309
 
 
1310
class cmd_upgrade(Command):
 
1311
    """Upgrade branch storage to current format.
 
1312
 
 
1313
    The check command or bzr developers may sometimes advise you to run
 
1314
    this command.
 
1315
 
 
1316
    This version of this command upgrades from the full-text storage
 
1317
    used by bzr 0.0.8 and earlier to the weave format (v5).
 
1318
    """
 
1319
    takes_args = ['dir?']
 
1320
 
 
1321
    def run(self, dir='.'):
 
1322
        from bzrlib.upgrade import upgrade
 
1323
        upgrade(dir)
 
1324
 
 
1325
 
 
1326
class cmd_whoami(Command):
 
1327
    """Show bzr user id."""
 
1328
    takes_options = ['email']
 
1329
    
 
1330
    @display_command
 
1331
    def run(self, email=False):
 
1332
        try:
 
1333
            b = WorkingTree.open_containing('.')[0].branch
 
1334
            config = bzrlib.config.BranchConfig(b)
 
1335
        except NotBranchError:
 
1336
            config = bzrlib.config.GlobalConfig()
 
1337
        
 
1338
        if email:
 
1339
            print config.user_email()
 
1340
        else:
 
1341
            print config.username()
 
1342
 
 
1343
class cmd_nick(Command):
 
1344
    """\
 
1345
    Print or set the branch nickname.  
 
1346
    If unset, the tree root directory name is used as the nickname
 
1347
    To print the current nickname, execute with no argument.  
 
1348
    """
 
1349
    takes_args = ['nickname?']
 
1350
    def run(self, nickname=None):
 
1351
        branch = Branch.open_containing('.')[0]
 
1352
        if nickname is None:
 
1353
            self.printme(branch)
 
1354
        else:
 
1355
            branch.nick = nickname
 
1356
 
 
1357
    @display_command
 
1358
    def printme(self, branch):
 
1359
        print branch.nick 
 
1360
 
 
1361
class cmd_selftest(Command):
 
1362
    """Run internal test suite.
 
1363
    
 
1364
    This creates temporary test directories in the working directory,
 
1365
    but not existing data is affected.  These directories are deleted
 
1366
    if the tests pass, or left behind to help in debugging if they
 
1367
    fail and --keep-output is specified.
 
1368
    
 
1369
    If arguments are given, they are regular expressions that say
 
1370
    which tests should run.
 
1371
    """
 
1372
    # TODO: --list should give a list of all available tests
 
1373
    hidden = True
 
1374
    takes_args = ['testspecs*']
 
1375
    takes_options = ['verbose', 
 
1376
                     Option('one', help='stop when one test fails'),
 
1377
                     Option('keep-output', 
 
1378
                            help='keep output directories when tests fail')
 
1379
                    ]
 
1380
 
 
1381
    def run(self, testspecs_list=None, verbose=False, one=False,
 
1382
            keep_output=False):
 
1383
        import bzrlib.ui
 
1384
        from bzrlib.tests import selftest
 
1385
        # we don't want progress meters from the tests to go to the
 
1386
        # real output; and we don't want log messages cluttering up
 
1387
        # the real logs.
 
1388
        save_ui = bzrlib.ui.ui_factory
 
1389
        bzrlib.trace.info('running tests...')
 
1390
        try:
 
1391
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
1392
            if testspecs_list is not None:
 
1393
                pattern = '|'.join(testspecs_list)
 
1394
            else:
 
1395
                pattern = ".*"
 
1396
            result = selftest(verbose=verbose, 
 
1397
                              pattern=pattern,
 
1398
                              stop_on_failure=one, 
 
1399
                              keep_output=keep_output)
 
1400
            if result:
 
1401
                bzrlib.trace.info('tests passed')
 
1402
            else:
 
1403
                bzrlib.trace.info('tests failed')
 
1404
            return int(not result)
 
1405
        finally:
 
1406
            bzrlib.ui.ui_factory = save_ui
 
1407
 
 
1408
 
 
1409
def show_version():
 
1410
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1411
    # is bzrlib itself in a branch?
 
1412
    bzrrev = bzrlib.get_bzr_revision()
 
1413
    if bzrrev:
 
1414
        print "  (bzr checkout, revision %d {%s})" % bzrrev
 
1415
    print bzrlib.__copyright__
 
1416
    print "http://bazaar-ng.org/"
 
1417
    print
 
1418
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
1419
    print "you may use, modify and redistribute it under the terms of the GNU"
 
1420
    print "General Public License version 2 or later."
 
1421
 
 
1422
 
 
1423
class cmd_version(Command):
 
1424
    """Show version of bzr."""
 
1425
    @display_command
 
1426
    def run(self):
 
1427
        show_version()
 
1428
 
 
1429
class cmd_rocks(Command):
 
1430
    """Statement of optimism."""
 
1431
    hidden = True
 
1432
    @display_command
 
1433
    def run(self):
 
1434
        print "it sure does!"
 
1435
 
 
1436
 
 
1437
class cmd_find_merge_base(Command):
 
1438
    """Find and print a base revision for merging two branches.
 
1439
    """
 
1440
    # TODO: Options to specify revisions on either side, as if
 
1441
    #       merging only part of the history.
 
1442
    takes_args = ['branch', 'other']
 
1443
    hidden = True
 
1444
    
 
1445
    @display_command
 
1446
    def run(self, branch, other):
 
1447
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
 
1448
        
 
1449
        branch1 = Branch.open_containing(branch)[0]
 
1450
        branch2 = Branch.open_containing(other)[0]
 
1451
 
 
1452
        history_1 = branch1.revision_history()
 
1453
        history_2 = branch2.revision_history()
 
1454
 
 
1455
        last1 = branch1.last_revision()
 
1456
        last2 = branch2.last_revision()
 
1457
 
 
1458
        source = MultipleRevisionSources(branch1, branch2)
 
1459
        
 
1460
        base_rev_id = common_ancestor(last1, last2, source)
 
1461
 
 
1462
        print 'merge base is revision %s' % base_rev_id
 
1463
        
 
1464
        return
 
1465
 
 
1466
        if base_revno is None:
 
1467
            raise bzrlib.errors.UnrelatedBranches()
 
1468
 
 
1469
        print ' r%-6d in %s' % (base_revno, branch)
 
1470
 
 
1471
        other_revno = branch2.revision_id_to_revno(base_revid)
 
1472
        
 
1473
        print ' r%-6d in %s' % (other_revno, other)
 
1474
 
 
1475
 
 
1476
 
 
1477
class cmd_merge(Command):
 
1478
    """Perform a three-way merge.
 
1479
    
 
1480
    The branch is the branch you will merge from.  By default, it will
 
1481
    merge the latest revision.  If you specify a revision, that
 
1482
    revision will be merged.  If you specify two revisions, the first
 
1483
    will be used as a BASE, and the second one as OTHER.  Revision
 
1484
    numbers are always relative to the specified branch.
 
1485
 
 
1486
    By default bzr will try to merge in all new work from the other
 
1487
    branch, automatically determining an appropriate base.  If this
 
1488
    fails, you may need to give an explicit base.
 
1489
    
 
1490
    Examples:
 
1491
 
 
1492
    To merge the latest revision from bzr.dev
 
1493
    bzr merge ../bzr.dev
 
1494
 
 
1495
    To merge changes up to and including revision 82 from bzr.dev
 
1496
    bzr merge -r 82 ../bzr.dev
 
1497
 
 
1498
    To merge the changes introduced by 82, without previous changes:
 
1499
    bzr merge -r 81..82 ../bzr.dev
 
1500
    
 
1501
    merge refuses to run if there are any uncommitted changes, unless
 
1502
    --force is given.
 
1503
    """
 
1504
    takes_args = ['branch?']
 
1505
    takes_options = ['revision', 'force', 'merge-type', 'reprocess',
 
1506
                     Option('show-base', help="Show base revision text in "
 
1507
                            "conflicts")]
 
1508
 
 
1509
    def run(self, branch=None, revision=None, force=False, merge_type=None,
 
1510
            show_base=False, reprocess=False):
 
1511
        from bzrlib.merge import merge
 
1512
        from bzrlib.merge_core import ApplyMerge3
 
1513
        if merge_type is None:
 
1514
            merge_type = ApplyMerge3
 
1515
        if branch is None:
 
1516
            branch = WorkingTree.open_containing('.')[0].branch.get_parent()
 
1517
            if branch is None:
 
1518
                raise BzrCommandError("No merge location known or specified.")
 
1519
            else:
 
1520
                print "Using saved location: %s" % branch 
 
1521
        if revision is None or len(revision) < 1:
 
1522
            base = [None, None]
 
1523
            other = [branch, -1]
 
1524
        else:
 
1525
            if len(revision) == 1:
 
1526
                base = [None, None]
 
1527
                other_branch = Branch.open_containing(branch)[0]
 
1528
                revno = revision[0].in_history(other_branch).revno
 
1529
                other = [branch, revno]
 
1530
            else:
 
1531
                assert len(revision) == 2
 
1532
                if None in revision:
 
1533
                    raise BzrCommandError(
 
1534
                        "Merge doesn't permit that revision specifier.")
 
1535
                b = Branch.open_containing(branch)[0]
 
1536
 
 
1537
                base = [branch, revision[0].in_history(b).revno]
 
1538
                other = [branch, revision[1].in_history(b).revno]
 
1539
 
 
1540
        try:
 
1541
            conflict_count = merge(other, base, check_clean=(not force),
 
1542
                                   merge_type=merge_type, reprocess=reprocess,
 
1543
                                   show_base=show_base)
 
1544
            if conflict_count != 0:
 
1545
                return 1
 
1546
            else:
 
1547
                return 0
 
1548
        except bzrlib.errors.AmbiguousBase, e:
 
1549
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
1550
                 "candidates are:\n  "
 
1551
                 + "\n  ".join(e.bases)
 
1552
                 + "\n"
 
1553
                 "please specify an explicit base with -r,\n"
 
1554
                 "and (if you want) report this to the bzr developers\n")
 
1555
            log_error(m)
 
1556
 
 
1557
 
 
1558
class cmd_remerge(Command):
 
1559
    """Redo a merge.
 
1560
    """
 
1561
    takes_args = ['file*']
 
1562
    takes_options = ['merge-type', 'reprocess',
 
1563
                     Option('show-base', help="Show base revision text in "
 
1564
                            "conflicts")]
 
1565
 
 
1566
    def run(self, file_list=None, merge_type=None, show_base=False,
 
1567
            reprocess=False):
 
1568
        from bzrlib.merge import merge_inner, transform_tree
 
1569
        from bzrlib.merge_core import ApplyMerge3
 
1570
        if merge_type is None:
 
1571
            merge_type = ApplyMerge3
 
1572
        tree, file_list = tree_files(file_list)
 
1573
        tree.lock_write()
 
1574
        try:
 
1575
            pending_merges = tree.pending_merges() 
 
1576
            if len(pending_merges) != 1:
 
1577
                raise BzrCommandError("Sorry, remerge only works after normal"
 
1578
                                      + " merges.  Not cherrypicking or"
 
1579
                                      + "multi-merges.")
 
1580
            base_revision = common_ancestor(tree.branch.last_revision(), 
 
1581
                                            pending_merges[0], tree.branch)
 
1582
            base_tree = tree.branch.revision_tree(base_revision)
 
1583
            other_tree = tree.branch.revision_tree(pending_merges[0])
 
1584
            interesting_ids = None
 
1585
            if file_list is not None:
 
1586
                interesting_ids = set()
 
1587
                for filename in file_list:
 
1588
                    file_id = tree.path2id(filename)
 
1589
                    interesting_ids.add(file_id)
 
1590
                    if tree.kind(file_id) != "directory":
 
1591
                        continue
 
1592
                    
 
1593
                    for name, ie in tree.inventory.iter_entries(file_id):
 
1594
                        interesting_ids.add(ie.file_id)
 
1595
            transform_tree(tree, tree.branch.basis_tree(), interesting_ids)
 
1596
            if file_list is None:
 
1597
                restore_files = list(tree.iter_conflicts())
 
1598
            else:
 
1599
                restore_files = file_list
 
1600
            for filename in restore_files:
 
1601
                try:
 
1602
                    restore(tree.abspath(filename))
 
1603
                except NotConflicted:
 
1604
                    pass
 
1605
            conflicts =  merge_inner(tree.branch, other_tree, base_tree, 
 
1606
                                     interesting_ids = interesting_ids, 
 
1607
                                     other_rev_id=pending_merges[0], 
 
1608
                                     merge_type=merge_type, 
 
1609
                                     show_base=show_base,
 
1610
                                     reprocess=reprocess)
 
1611
        finally:
 
1612
            tree.unlock()
 
1613
        if conflicts > 0:
 
1614
            return 1
 
1615
        else:
 
1616
            return 0
 
1617
 
 
1618
class cmd_revert(Command):
 
1619
    """Reverse all changes since the last commit.
 
1620
 
 
1621
    Only versioned files are affected.  Specify filenames to revert only 
 
1622
    those files.  By default, any files that are changed will be backed up
 
1623
    first.  Backup files have a '~' appended to their name.
 
1624
    """
 
1625
    takes_options = ['revision', 'no-backup']
 
1626
    takes_args = ['file*']
 
1627
    aliases = ['merge-revert']
 
1628
 
 
1629
    def run(self, revision=None, no_backup=False, file_list=None):
 
1630
        from bzrlib.merge import merge_inner
 
1631
        from bzrlib.commands import parse_spec
 
1632
        if file_list is not None:
 
1633
            if len(file_list) == 0:
 
1634
                raise BzrCommandError("No files specified")
 
1635
        else:
 
1636
            file_list = []
 
1637
        if revision is None:
 
1638
            revno = -1
 
1639
            tree = WorkingTree.open_containing('.')[0]
 
1640
            # FIXME should be tree.last_revision
 
1641
            rev_id = tree.branch.last_revision()
 
1642
        elif len(revision) != 1:
 
1643
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
1644
        else:
 
1645
            tree, file_list = tree_files(file_list)
 
1646
            rev_id = revision[0].in_history(tree.branch).rev_id
 
1647
        tree.revert(file_list, tree.branch.revision_tree(rev_id),
 
1648
                                not no_backup)
 
1649
 
 
1650
 
 
1651
class cmd_assert_fail(Command):
 
1652
    """Test reporting of assertion failures"""
 
1653
    hidden = True
 
1654
    def run(self):
 
1655
        assert False, "always fails"
 
1656
 
 
1657
 
 
1658
class cmd_help(Command):
 
1659
    """Show help on a command or other topic.
 
1660
 
 
1661
    For a list of all available commands, say 'bzr help commands'."""
 
1662
    takes_options = ['long']
 
1663
    takes_args = ['topic?']
 
1664
    aliases = ['?']
 
1665
    
 
1666
    @display_command
 
1667
    def run(self, topic=None, long=False):
 
1668
        import help
 
1669
        if topic is None and long:
 
1670
            topic = "commands"
 
1671
        help.help(topic)
 
1672
 
 
1673
 
 
1674
class cmd_shell_complete(Command):
 
1675
    """Show appropriate completions for context.
 
1676
 
 
1677
    For a list of all available commands, say 'bzr shell-complete'."""
 
1678
    takes_args = ['context?']
 
1679
    aliases = ['s-c']
 
1680
    hidden = True
 
1681
    
 
1682
    @display_command
 
1683
    def run(self, context=None):
 
1684
        import shellcomplete
 
1685
        shellcomplete.shellcomplete(context)
 
1686
 
 
1687
 
 
1688
class cmd_fetch(Command):
 
1689
    """Copy in history from another branch but don't merge it.
 
1690
 
 
1691
    This is an internal method used for pull and merge."""
 
1692
    hidden = True
 
1693
    takes_args = ['from_branch', 'to_branch']
 
1694
    def run(self, from_branch, to_branch):
 
1695
        from bzrlib.fetch import Fetcher
 
1696
        from bzrlib.branch import Branch
 
1697
        from_b = Branch.open(from_branch)
 
1698
        to_b = Branch.open(to_branch)
 
1699
        from_b.lock_read()
 
1700
        try:
 
1701
            to_b.lock_write()
 
1702
            try:
 
1703
                Fetcher(to_b, from_b)
 
1704
            finally:
 
1705
                to_b.unlock()
 
1706
        finally:
 
1707
            from_b.unlock()
 
1708
 
 
1709
 
 
1710
class cmd_missing(Command):
 
1711
    """What is missing in this branch relative to other branch.
 
1712
    """
 
1713
    # TODO: rewrite this in terms of ancestry so that it shows only
 
1714
    # unmerged things
 
1715
    
 
1716
    takes_args = ['remote?']
 
1717
    aliases = ['mis', 'miss']
 
1718
    takes_options = ['verbose']
 
1719
 
 
1720
    @display_command
 
1721
    def run(self, remote=None, verbose=False):
 
1722
        from bzrlib.errors import BzrCommandError
 
1723
        from bzrlib.missing import show_missing
 
1724
 
 
1725
        if verbose and is_quiet():
 
1726
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
1727
 
 
1728
        tree = WorkingTree.open_containing('.')[0]
 
1729
        parent = tree.branch.get_parent()
 
1730
        if remote is None:
 
1731
            if parent is None:
 
1732
                raise BzrCommandError("No missing location known or specified.")
 
1733
            else:
 
1734
                if not is_quiet():
 
1735
                    print "Using last location: %s" % parent
 
1736
                remote = parent
 
1737
        elif parent is None:
 
1738
            # We only update parent if it did not exist, missing
 
1739
            # should not change the parent
 
1740
            tree.branch.set_parent(remote)
 
1741
        br_remote = Branch.open_containing(remote)[0]
 
1742
        return show_missing(tree.branch, br_remote, verbose=verbose, 
 
1743
                            quiet=is_quiet())
 
1744
 
 
1745
 
 
1746
class cmd_plugins(Command):
 
1747
    """List plugins"""
 
1748
    hidden = True
 
1749
    @display_command
 
1750
    def run(self):
 
1751
        import bzrlib.plugin
 
1752
        from inspect import getdoc
 
1753
        for plugin in bzrlib.plugin.all_plugins:
 
1754
            if hasattr(plugin, '__path__'):
 
1755
                print plugin.__path__[0]
 
1756
            elif hasattr(plugin, '__file__'):
 
1757
                print plugin.__file__
 
1758
            else:
 
1759
                print `plugin`
 
1760
                
 
1761
            d = getdoc(plugin)
 
1762
            if d:
 
1763
                print '\t', d.split('\n')[0]
 
1764
 
 
1765
 
 
1766
class cmd_testament(Command):
 
1767
    """Show testament (signing-form) of a revision."""
 
1768
    takes_options = ['revision', 'long']
 
1769
    takes_args = ['branch?']
 
1770
    @display_command
 
1771
    def run(self, branch='.', revision=None, long=False):
 
1772
        from bzrlib.testament import Testament
 
1773
        b = WorkingTree.open_containing(branch)[0].branch
 
1774
        b.lock_read()
 
1775
        try:
 
1776
            if revision is None:
 
1777
                rev_id = b.last_revision()
 
1778
            else:
 
1779
                rev_id = revision[0].in_history(b).rev_id
 
1780
            t = Testament.from_revision(b, rev_id)
 
1781
            if long:
 
1782
                sys.stdout.writelines(t.as_text_lines())
 
1783
            else:
 
1784
                sys.stdout.write(t.as_short_text())
 
1785
        finally:
 
1786
            b.unlock()
 
1787
 
 
1788
 
 
1789
class cmd_annotate(Command):
 
1790
    """Show the origin of each line in a file.
 
1791
 
 
1792
    This prints out the given file with an annotation on the left side
 
1793
    indicating which revision, author and date introduced the change.
 
1794
 
 
1795
    If the origin is the same for a run of consecutive lines, it is 
 
1796
    shown only at the top, unless the --all option is given.
 
1797
    """
 
1798
    # TODO: annotate directories; showing when each file was last changed
 
1799
    # TODO: annotate a previous version of a file
 
1800
    # TODO: if the working copy is modified, show annotations on that 
 
1801
    #       with new uncommitted lines marked
 
1802
    aliases = ['blame', 'praise']
 
1803
    takes_args = ['filename']
 
1804
    takes_options = [Option('all', help='show annotations on all lines'),
 
1805
                     Option('long', help='show date in annotations'),
 
1806
                     ]
 
1807
 
 
1808
    @display_command
 
1809
    def run(self, filename, all=False, long=False):
 
1810
        from bzrlib.annotate import annotate_file
 
1811
        tree, relpath = WorkingTree.open_containing(filename)
 
1812
        branch = tree.branch
 
1813
        branch.lock_read()
 
1814
        try:
 
1815
            file_id = tree.inventory.path2id(relpath)
 
1816
            tree = branch.revision_tree(branch.last_revision())
 
1817
            file_version = tree.inventory[file_id].revision
 
1818
            annotate_file(branch, file_version, file_id, long, all, sys.stdout)
 
1819
        finally:
 
1820
            branch.unlock()
 
1821
 
 
1822
 
 
1823
class cmd_re_sign(Command):
 
1824
    """Create a digital signature for an existing revision."""
 
1825
    # TODO be able to replace existing ones.
 
1826
 
 
1827
    hidden = True # is this right ?
 
1828
    takes_args = ['revision_id?']
 
1829
    takes_options = ['revision']
 
1830
    
 
1831
    def run(self, revision_id=None, revision=None):
 
1832
        import bzrlib.config as config
 
1833
        import bzrlib.gpg as gpg
 
1834
        if revision_id is not None and revision is not None:
 
1835
            raise BzrCommandError('You can only supply one of revision_id or --revision')
 
1836
        if revision_id is None and revision is None:
 
1837
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
1838
        b = WorkingTree.open_containing('.')[0].branch
 
1839
        gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
 
1840
        if revision_id is not None:
 
1841
            b.sign_revision(revision_id, gpg_strategy)
 
1842
        elif revision is not None:
 
1843
            if len(revision) == 1:
 
1844
                revno, rev_id = revision[0].in_history(b)
 
1845
                b.sign_revision(rev_id, gpg_strategy)
 
1846
            elif len(revision) == 2:
 
1847
                # are they both on rh- if so we can walk between them
 
1848
                # might be nice to have a range helper for arbitrary
 
1849
                # revision paths. hmm.
 
1850
                from_revno, from_revid = revision[0].in_history(b)
 
1851
                to_revno, to_revid = revision[1].in_history(b)
 
1852
                if to_revid is None:
 
1853
                    to_revno = b.revno()
 
1854
                if from_revno is None or to_revno is None:
 
1855
                    raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
 
1856
                for revno in range(from_revno, to_revno + 1):
 
1857
                    b.sign_revision(b.get_rev_id(revno), gpg_strategy)
 
1858
            else:
 
1859
                raise BzrCommandError('Please supply either one revision, or a range.')
 
1860
 
 
1861
 
 
1862
class cmd_uncommit(bzrlib.commands.Command):
 
1863
    """Remove the last committed revision.
 
1864
 
 
1865
    By supplying the --all flag, it will not only remove the entry 
 
1866
    from revision_history, but also remove all of the entries in the
 
1867
    stores.
 
1868
 
 
1869
    --verbose will print out what is being removed.
 
1870
    --dry-run will go through all the motions, but not actually
 
1871
    remove anything.
 
1872
    
 
1873
    In the future, uncommit will create a changeset, which can then
 
1874
    be re-applied.
 
1875
    """
 
1876
    takes_options = ['all', 'verbose', 'revision',
 
1877
                    Option('dry-run', help='Don\'t actually make changes'),
 
1878
                    Option('force', help='Say yes to all questions.')]
 
1879
    takes_args = ['location?']
 
1880
    aliases = []
 
1881
 
 
1882
    def run(self, location=None, all=False,
 
1883
            dry_run=False, verbose=False,
 
1884
            revision=None, force=False):
 
1885
        from bzrlib.branch import Branch
 
1886
        from bzrlib.log import log_formatter
 
1887
        import sys
 
1888
        from bzrlib.uncommit import uncommit
 
1889
 
 
1890
        if location is None:
 
1891
            location = '.'
 
1892
        b, relpath = Branch.open_containing(location)
 
1893
 
 
1894
        if revision is None:
 
1895
            revno = b.revno()
 
1896
            rev_id = b.last_revision()
 
1897
        else:
 
1898
            revno, rev_id = revision[0].in_history(b)
 
1899
        if rev_id is None:
 
1900
            print 'No revisions to uncommit.'
 
1901
 
 
1902
        for r in range(revno, b.revno()+1):
 
1903
            rev_id = b.get_rev_id(r)
 
1904
            lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
 
1905
            lf.show(r, b.get_revision(rev_id), None)
 
1906
 
 
1907
        if dry_run:
 
1908
            print 'Dry-run, pretending to remove the above revisions.'
 
1909
            if not force:
 
1910
                val = raw_input('Press <enter> to continue')
 
1911
        else:
 
1912
            print 'The above revision(s) will be removed.'
 
1913
            if not force:
 
1914
                val = raw_input('Are you sure [y/N]? ')
 
1915
                if val.lower() not in ('y', 'yes'):
 
1916
                    print 'Canceled'
 
1917
                    return 0
 
1918
 
 
1919
        uncommit(b, remove_files=all,
 
1920
                dry_run=dry_run, verbose=verbose,
 
1921
                revno=revno)
 
1922
 
 
1923
 
 
1924
# these get imported and then picked up by the scan for cmd_*
 
1925
# TODO: Some more consistent way to split command definitions across files;
 
1926
# we do need to load at least some information about them to know of 
 
1927
# aliases.
 
1928
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore