~ubuntu-branches/ubuntu/hardy/bzr/hardy-updates

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Bazaar Package Importer
  • Author(s): Jeff Bailey
  • Date: 2005-11-07 13:17:53 UTC
  • Revision ID: james.westby@ubuntu.com-20051107131753-qsy145z1rfug5i27
Tags: upstream-0.6.2
ImportĀ upstreamĀ versionĀ 0.6.2

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