/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

Include new submodules in setup.py list of modules.

Show diffs side-by-side

added added

removed removed

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