/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

Dont use Branch.open in smart_add when checking for child trees.

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