/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

Merge from mpool.

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