/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] basic_io metaformat (mbp)

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