/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

[bug 3632] Matthieu Moy- bzr cat should default to last revision

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