/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

Updated the test to also test zip exports. Fixed some small bugs exposed by test suite.

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