/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

  • Committer: Aaron Bentley
  • Date: 2005-11-19 22:56:37 UTC
  • mto: (1185.33.34 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 1510.
  • Revision ID: aaron.bentley@utoronto.ca-20051119225637-e7afc16a06a31b59
Fixed fetch to be safer wrt ghosts and corrupt branches

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