/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

MergeĀ fromĀ mainline

Show diffs side-by-side

added added

removed removed

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