1
# Copyright (C) 2004, 2005 by Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
# DO NOT change this to cStringIO - it results in control files 
 
 
19
# FIXIT! (Only deal with byte streams OR unicode at any one layer.)
 
 
21
from StringIO import StringIO
 
 
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
 
 
36
from bzrlib.trace import mutter, note, log_error, warning
 
 
37
from bzrlib.workingtree import WorkingTree
 
 
40
def branch_files(file_list, default_branch='.'):
 
 
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]))
 
 
47
def inner_branch_files(file_list, default_branch='.'):
 
 
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.
 
 
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]
 
 
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)
 
 
63
    for filename in file_list:
 
 
64
        new_list.append(tree.relpath(filename))
 
 
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
 
 
74
class cmd_status(Command):
 
 
75
    """Display status summary.
 
 
77
    This reports on versioned and unknown files, reporting them
 
 
78
    grouped by state.  Possible states are:
 
 
81
        Versioned in the working copy but not in the previous revision.
 
 
84
        Versioned in the previous revision but removed or deleted
 
 
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.
 
 
93
        Text has changed since the previous revision.
 
 
96
        Nothing about this file has changed since the previous revision.
 
 
97
        Only shown with --all.
 
 
100
        Not versioned and not matching an ignore pattern.
 
 
102
    To see ignored files use 'bzr ignored'.  For details in the
 
 
103
    changes to file texts, use 'bzr diff'.
 
 
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.
 
 
110
    If a revision argument is given, the status is calculated against
 
 
111
    that revision, or between two revisions if two are provided.
 
 
114
    # TODO: --no-recurse, --recurse options
 
 
116
    takes_args = ['file*']
 
 
117
    takes_options = ['all', 'show-ids', 'revision']
 
 
118
    aliases = ['st', 'stat']
 
 
121
    def run(self, all=False, show_ids=False, file_list=None, revision=None):
 
 
122
        b, file_list = branch_files(file_list)
 
 
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)
 
 
129
class cmd_cat_revision(Command):
 
 
130
    """Write out metadata for a revision.
 
 
132
    The revision to print can either be specified by a specific
 
 
133
    revision identifier, or you can use --revision.
 
 
137
    takes_args = ['revision_id?']
 
 
138
    takes_options = ['revision']
 
 
141
    def run(self, revision_id=None, revision=None):
 
 
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(revision_id))
 
 
150
        elif revision is not 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(rev_id))
 
 
158
class cmd_revno(Command):
 
 
159
    """Show current revision number.
 
 
161
    This is equal to the number of revisions on this branch."""
 
 
164
        print Branch.open_containing('.')[0].revno()
 
 
167
class cmd_revision_info(Command):
 
 
168
    """Show revision number and revision id for a given revision identifier.
 
 
171
    takes_args = ['revision_info*']
 
 
172
    takes_options = ['revision']
 
 
174
    def run(self, revision=None, revision_info_list=[]):
 
 
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))
 
 
183
            raise BzrCommandError('You must supply a revision identifier')
 
 
185
        b = Branch.open_containing('.')[0]
 
 
188
            revinfo = rev.in_history(b)
 
 
189
            if revinfo.revno is None:
 
 
190
                print '     %s' % revinfo.rev_id
 
 
192
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
 
195
class cmd_add(Command):
 
 
196
    """Add specified files or directories.
 
 
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.
 
 
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.
 
 
210
    Therefore simply saying 'bzr add' will version all files that
 
 
211
    are currently unknown.
 
 
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.
 
 
218
    takes_args = ['file*']
 
 
219
    takes_options = ['no-recurse', 'quiet']
 
 
221
    def run(self, file_list, no_recurse=False, quiet=False):
 
 
222
        from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
 
 
224
            reporter = add_reporter_null
 
 
226
            reporter = add_reporter_print
 
 
227
        smart_add(file_list, not no_recurse, reporter)
 
 
230
class cmd_mkdir(Command):
 
 
231
    """Create a new versioned directory.
 
 
233
    This is equivalent to creating the directory and then adding it.
 
 
235
    takes_args = ['dir+']
 
 
237
    def run(self, dir_list):
 
 
242
            b, dd = Branch.open_containing(d)
 
 
247
class cmd_relpath(Command):
 
 
248
    """Show path of a file relative to root"""
 
 
249
    takes_args = ['filename']
 
 
253
    def run(self, filename):
 
 
254
        branch, relpath = Branch.open_containing(filename)
 
 
258
class cmd_inventory(Command):
 
 
259
    """Show inventory of the current working copy or a revision."""
 
 
260
    takes_options = ['revision', 'show-ids']
 
 
263
    def run(self, revision=None, show_ids=False):
 
 
264
        b = Branch.open_containing('.')[0]
 
 
266
            inv = b.working_tree().read_working_inventory()
 
 
268
            if len(revision) > 1:
 
 
269
                raise BzrCommandError('bzr inventory --revision takes'
 
 
270
                    ' exactly one revision identifier')
 
 
271
            inv = b.get_revision_inventory(revision[0].in_history(b).rev_id)
 
 
273
        for path, entry in inv.entries():
 
 
275
                print '%-50s %s' % (path, entry.file_id)
 
 
280
class cmd_move(Command):
 
 
281
    """Move files to a different directory.
 
 
286
    The destination must be a versioned directory in the same branch.
 
 
288
    takes_args = ['source$', 'dest']
 
 
289
    def run(self, source_list, dest):
 
 
290
        b, source_list = branch_files(source_list)
 
 
292
        # TODO: glob expansion on windows?
 
 
293
        tree = WorkingTree(b.base, b)
 
 
294
        b.move(source_list, tree.relpath(dest))
 
 
297
class cmd_rename(Command):
 
 
298
    """Change the name of an entry.
 
 
301
      bzr rename frob.c frobber.c
 
 
302
      bzr rename src/frob.c lib/frob.c
 
 
304
    It is an error if the destination name exists.
 
 
306
    See also the 'move' command, which moves files into a different
 
 
307
    directory without changing their name.
 
 
309
    # TODO: Some way to rename multiple files without invoking 
 
 
310
    # bzr for each one?"""
 
 
311
    takes_args = ['from_name', 'to_name']
 
 
313
    def run(self, from_name, to_name):
 
 
314
        b, (from_name, to_name) = branch_files((from_name, to_name))
 
 
315
        b.rename_one(from_name, to_name)
 
 
318
class cmd_mv(Command):
 
 
319
    """Move or rename a file.
 
 
322
        bzr mv OLDNAME NEWNAME
 
 
323
        bzr mv SOURCE... DESTINATION
 
 
325
    If the last argument is a versioned directory, all the other names
 
 
326
    are moved into it.  Otherwise, there must be exactly two arguments
 
 
327
    and the file is changed to a new name, which must not already exist.
 
 
329
    Files cannot be moved between branches.
 
 
331
    takes_args = ['names*']
 
 
332
    def run(self, names_list):
 
 
333
        if len(names_list) < 2:
 
 
334
            raise BzrCommandError("missing file argument")
 
 
335
        b, rel_names = branch_files(names_list)
 
 
337
        if os.path.isdir(names_list[-1]):
 
 
338
            # move into existing directory
 
 
339
            for pair in b.move(rel_names[:-1], rel_names[-1]):
 
 
340
                print "%s => %s" % pair
 
 
342
            if len(names_list) != 2:
 
 
343
                raise BzrCommandError('to mv multiple files the destination '
 
 
344
                                      'must be a versioned directory')
 
 
345
            b.rename_one(rel_names[0], rel_names[1])
 
 
346
            print "%s => %s" % (rel_names[0], rel_names[1])
 
 
349
class cmd_pull(Command):
 
 
350
    """Pull any changes from another branch into the current one.
 
 
352
    If there is no default location set, the first pull will set it.  After
 
 
353
    that, you can omit the location to use the default.  To change the
 
 
354
    default, use --remember.
 
 
356
    This command only works on branches that have not diverged.  Branches are
 
 
357
    considered diverged if both branches have had commits without first
 
 
358
    pulling from the other.
 
 
360
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
 
361
    from one into the other.  Once one branch has merged, the other should
 
 
362
    be able to pull it again.
 
 
364
    If you want to forget your local changes and just update your branch to
 
 
365
    match the remote one, use --overwrite.
 
 
367
    takes_options = ['remember', 'overwrite', 'verbose']
 
 
368
    takes_args = ['location?']
 
 
370
    def run(self, location=None, remember=False, overwrite=False, verbose=False):
 
 
371
        from bzrlib.merge import merge
 
 
372
        from shutil import rmtree
 
 
375
        br_to = Branch.open_containing('.')[0]
 
 
376
        stored_loc = br_to.get_parent()
 
 
378
            if stored_loc is None:
 
 
379
                raise BzrCommandError("No pull location known or specified.")
 
 
381
                print "Using saved location: %s" % stored_loc
 
 
382
                location = stored_loc
 
 
383
        br_from = Branch.open(location)
 
 
385
            old_rh = br_to.revision_history()
 
 
386
            br_to.working_tree().pull(br_from, overwrite)
 
 
387
        except DivergedBranches:
 
 
388
            raise BzrCommandError("These branches have diverged."
 
 
390
        if br_to.get_parent() is None or remember:
 
 
391
            br_to.set_parent(location)
 
 
394
            new_rh = br_to.revision_history()
 
 
397
                from bzrlib.log import show_changed_revisions
 
 
398
                show_changed_revisions(br_to, old_rh, new_rh)
 
 
401
class cmd_push(Command):
 
 
402
    """Push this branch into another branch.
 
 
404
    The remote branch will not have its working tree populated because this
 
 
405
    is both expensive, and may not be supported on the remote file system.
 
 
407
    Some smart servers or protocols *may* put the working tree in place.
 
 
409
    If there is no default push location set, the first push will set it.
 
 
410
    After that, you can omit the location to use the default.  To change the
 
 
411
    default, use --remember.
 
 
413
    This command only works on branches that have not diverged.  Branches are
 
 
414
    considered diverged if the branch being pushed to is not an older version
 
 
417
    If branches have diverged, you can use 'bzr push --overwrite' to replace
 
 
418
    the other branch completely.
 
 
420
    If you want to ensure you have the different changes in the other branch,
 
 
421
    do a merge (see bzr help merge) from the other branch, and commit that
 
 
422
    before doing a 'push --overwrite'.
 
 
424
    takes_options = ['remember', 'overwrite', 
 
 
425
                     Option('create-prefix', 
 
 
426
                            help='Create the path leading up to the branch '
 
 
427
                                 'if it does not already exist')]
 
 
428
    takes_args = ['location?']
 
 
430
    def run(self, location=None, remember=False, overwrite=False,
 
 
431
            create_prefix=False, verbose=False):
 
 
433
        from shutil import rmtree
 
 
434
        from bzrlib.transport import get_transport
 
 
436
        br_from = Branch.open_containing('.')[0]
 
 
437
        stored_loc = br_from.get_push_location()
 
 
439
            if stored_loc is None:
 
 
440
                raise BzrCommandError("No push location known or specified.")
 
 
442
                print "Using saved location: %s" % stored_loc
 
 
443
                location = stored_loc
 
 
445
            br_to = Branch.open(location)
 
 
446
        except NotBranchError:
 
 
448
            transport = get_transport(location).clone('..')
 
 
449
            if not create_prefix:
 
 
451
                    transport.mkdir(transport.relpath(location))
 
 
453
                    raise BzrCommandError("Parent directory of %s "
 
 
454
                                          "does not exist." % location)
 
 
456
                current = transport.base
 
 
457
                needed = [(transport, transport.relpath(location))]
 
 
460
                        transport, relpath = needed[-1]
 
 
461
                        transport.mkdir(relpath)
 
 
464
                        new_transport = transport.clone('..')
 
 
465
                        needed.append((new_transport,
 
 
466
                                       new_transport.relpath(transport.base)))
 
 
467
                        if new_transport.base == transport.base:
 
 
468
                            raise BzrCommandError("Could not creeate "
 
 
472
            br_to = Branch.initialize(location)
 
 
474
            old_rh = br_to.revision_history()
 
 
475
            br_to.pull(br_from, overwrite)
 
 
476
        except DivergedBranches:
 
 
477
            raise BzrCommandError("These branches have diverged."
 
 
478
                                  "  Try a merge then push with overwrite.")
 
 
479
        if br_from.get_push_location() is None or remember:
 
 
480
            br_from.set_push_location(location)
 
 
483
            new_rh = br_to.revision_history()
 
 
486
                from bzrlib.log import show_changed_revisions
 
 
487
                show_changed_revisions(br_to, old_rh, new_rh)
 
 
489
class cmd_branch(Command):
 
 
490
    """Create a new copy of a branch.
 
 
492
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
 
493
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
 
495
    To retrieve the branch as of a particular revision, supply the --revision
 
 
496
    parameter, as in "branch foo/bar -r 5".
 
 
498
    --basis is to speed up branching from remote branches.  When specified, it
 
 
499
    copies all the file-contents, inventory and revision data from the basis
 
 
500
    branch before copying anything from the remote branch.
 
 
502
    takes_args = ['from_location', 'to_location?']
 
 
503
    takes_options = ['revision', 'basis']
 
 
504
    aliases = ['get', 'clone']
 
 
506
    def run(self, from_location, to_location=None, revision=None, basis=None):
 
 
507
        from bzrlib.clone import copy_branch
 
 
509
        from shutil import rmtree
 
 
512
        elif len(revision) > 1:
 
 
513
            raise BzrCommandError(
 
 
514
                'bzr branch --revision takes exactly 1 revision value')
 
 
516
            br_from = Branch.open(from_location)
 
 
518
            if e.errno == errno.ENOENT:
 
 
519
                raise BzrCommandError('Source location "%s" does not'
 
 
520
                                      ' exist.' % to_location)
 
 
525
            if basis is not None:
 
 
526
                basis_branch = Branch.open_containing(basis)[0]
 
 
529
            if len(revision) == 1 and revision[0] is not None:
 
 
530
                revision_id = revision[0].in_history(br_from)[1]
 
 
533
            if to_location is None:
 
 
534
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
 
537
                name = os.path.basename(to_location) + '\n'
 
 
539
                os.mkdir(to_location)
 
 
541
                if e.errno == errno.EEXIST:
 
 
542
                    raise BzrCommandError('Target directory "%s" already'
 
 
543
                                          ' exists.' % to_location)
 
 
544
                if e.errno == errno.ENOENT:
 
 
545
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
 
550
                copy_branch(br_from, to_location, revision_id, basis_branch)
 
 
551
            except bzrlib.errors.NoSuchRevision:
 
 
553
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
 
 
554
                raise BzrCommandError(msg)
 
 
555
            except bzrlib.errors.UnlistableBranch:
 
 
557
                msg = "The branch %s cannot be used as a --basis"
 
 
558
                raise BzrCommandError(msg)
 
 
560
                branch = Branch.open(to_location)
 
 
561
                name = StringIO(name)
 
 
562
                branch.put_controlfile('branch-name', name)
 
 
567
class cmd_renames(Command):
 
 
568
    """Show list of renamed files.
 
 
570
    # TODO: Option to show renames between two historical versions.
 
 
572
    # TODO: Only show renames under dir, rather than in the whole branch.
 
 
573
    takes_args = ['dir?']
 
 
576
    def run(self, dir='.'):
 
 
577
        b = Branch.open_containing(dir)[0]
 
 
578
        old_inv = b.basis_tree().inventory
 
 
579
        new_inv = b.working_tree().read_working_inventory()
 
 
581
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
 
583
        for old_name, new_name in renames:
 
 
584
            print "%s => %s" % (old_name, new_name)        
 
 
587
class cmd_info(Command):
 
 
588
    """Show statistical information about a branch."""
 
 
589
    takes_args = ['branch?']
 
 
592
    def run(self, branch=None):
 
 
594
        b = Branch.open_containing(branch)[0]
 
 
598
class cmd_remove(Command):
 
 
599
    """Make a file unversioned.
 
 
601
    This makes bzr stop tracking changes to a versioned file.  It does
 
 
602
    not delete the working copy.
 
 
604
    takes_args = ['file+']
 
 
605
    takes_options = ['verbose']
 
 
608
    def run(self, file_list, verbose=False):
 
 
609
        b, file_list = branch_files(file_list)
 
 
610
        tree = b.working_tree()
 
 
611
        tree.remove(file_list, verbose=verbose)
 
 
614
class cmd_file_id(Command):
 
 
615
    """Print file_id of a particular file or directory.
 
 
617
    The file_id is assigned when the file is first added and remains the
 
 
618
    same through all revisions where the file exists, even when it is
 
 
622
    takes_args = ['filename']
 
 
624
    def run(self, filename):
 
 
625
        b, relpath = Branch.open_containing(filename)
 
 
626
        i = b.working_tree().inventory.path2id(relpath)
 
 
628
            raise BzrError("%r is not a versioned file" % filename)
 
 
633
class cmd_file_path(Command):
 
 
634
    """Print path of file_ids to a file or directory.
 
 
636
    This prints one line for each directory down to the target,
 
 
637
    starting at the branch root."""
 
 
639
    takes_args = ['filename']
 
 
641
    def run(self, filename):
 
 
642
        b, relpath = Branch.open_containing(filename)
 
 
644
        fid = inv.path2id(relpath)
 
 
646
            raise BzrError("%r is not a versioned file" % filename)
 
 
647
        for fip in inv.get_idpath(fid):
 
 
651
class cmd_revision_history(Command):
 
 
652
    """Display list of revision ids on this branch."""
 
 
656
        for patchid in Branch.open_containing('.')[0].revision_history():
 
 
660
class cmd_ancestry(Command):
 
 
661
    """List all revisions merged into this branch."""
 
 
665
        b = Branch.open_containing('.')[0]
 
 
666
        for revision_id in b.get_ancestry(b.last_revision()):
 
 
670
class cmd_directories(Command):
 
 
671
    """Display list of versioned directories in this branch."""
 
 
674
        for name, ie in (Branch.open_containing('.')[0].working_tree().
 
 
675
                         read_working_inventory().directories()):
 
 
682
class cmd_init(Command):
 
 
683
    """Make a directory into a versioned branch.
 
 
685
    Use this to create an empty branch, or before importing an
 
 
688
    Recipe for importing a tree of files:
 
 
693
        bzr commit -m 'imported project'
 
 
695
    takes_args = ['location?']
 
 
696
    def run(self, location=None):
 
 
697
        from bzrlib.branch import Branch
 
 
701
            # The path has to exist to initialize a
 
 
702
            # branch inside of it.
 
 
703
            # Just using os.mkdir, since I don't
 
 
704
            # believe that we want to create a bunch of
 
 
705
            # locations if the user supplies an extended path
 
 
706
            if not os.path.exists(location):
 
 
708
        Branch.initialize(location)
 
 
711
class cmd_diff(Command):
 
 
712
    """Show differences in working tree.
 
 
714
    If files are listed, only the changes in those files are listed.
 
 
715
    Otherwise, all changes for the tree are listed.
 
 
722
    # TODO: Allow diff across branches.
 
 
723
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
 
 
724
    #       or a graphical diff.
 
 
726
    # TODO: Python difflib is not exactly the same as unidiff; should
 
 
727
    #       either fix it up or prefer to use an external diff.
 
 
729
    # TODO: If a directory is given, diff everything under that.
 
 
731
    # TODO: Selected-file diff is inefficient and doesn't show you
 
 
734
    # TODO: This probably handles non-Unix newlines poorly.
 
 
736
    takes_args = ['file*']
 
 
737
    takes_options = ['revision', 'diff-options']
 
 
738
    aliases = ['di', 'dif']
 
 
741
    def run(self, revision=None, file_list=None, diff_options=None):
 
 
742
        from bzrlib.diff import show_diff
 
 
744
            b, file_list = inner_branch_files(file_list)
 
 
746
        except NotBranchError:
 
 
747
            if len(file_list) != 2:
 
 
748
                raise BzrCommandError("Files are in different branches")
 
 
750
            b, file1 = Branch.open_containing(file_list[0])
 
 
751
            b2, file2 = Branch.open_containing(file_list[1])
 
 
752
            if file1 != "" or file2 != "":
 
 
753
                raise BzrCommandError("Files are in different branches")
 
 
755
        if revision is not None:
 
 
757
                raise BzrCommandError("Can't specify -r with two branches")
 
 
758
            if len(revision) == 1:
 
 
759
                return show_diff(b, revision[0], specific_files=file_list,
 
 
760
                                 external_diff_options=diff_options)
 
 
761
            elif len(revision) == 2:
 
 
762
                return show_diff(b, revision[0], specific_files=file_list,
 
 
763
                                 external_diff_options=diff_options,
 
 
764
                                 revision2=revision[1])
 
 
766
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
 
768
            return show_diff(b, None, specific_files=file_list,
 
 
769
                             external_diff_options=diff_options, b2=b2)
 
 
772
class cmd_deleted(Command):
 
 
773
    """List files deleted in the working tree.
 
 
775
    # TODO: Show files deleted since a previous revision, or
 
 
776
    # between two revisions.
 
 
777
    # TODO: Much more efficient way to do this: read in new
 
 
778
    # directories with readdir, rather than stating each one.  Same
 
 
779
    # level of effort but possibly much less IO.  (Or possibly not,
 
 
780
    # if the directories are very large...)
 
 
782
    def run(self, show_ids=False):
 
 
783
        b = Branch.open_containing('.')[0]
 
 
785
        new = b.working_tree()
 
 
786
        for path, ie in old.inventory.iter_entries():
 
 
787
            if not new.has_id(ie.file_id):
 
 
789
                    print '%-50s %s' % (path, ie.file_id)
 
 
794
class cmd_modified(Command):
 
 
795
    """List files modified in working tree."""
 
 
799
        from bzrlib.delta import compare_trees
 
 
801
        b = Branch.open_containing('.')[0]
 
 
802
        td = compare_trees(b.basis_tree(), b.working_tree())
 
 
804
        for path, id, kind, text_modified, meta_modified in td.modified:
 
 
809
class cmd_added(Command):
 
 
810
    """List files added in working tree."""
 
 
814
        b = Branch.open_containing('.')[0]
 
 
815
        wt = b.working_tree()
 
 
816
        basis_inv = b.basis_tree().inventory
 
 
819
            if file_id in basis_inv:
 
 
821
            path = inv.id2path(file_id)
 
 
822
            if not os.access(b.abspath(path), os.F_OK):
 
 
828
class cmd_root(Command):
 
 
829
    """Show the tree root directory.
 
 
831
    The root is the nearest enclosing directory with a .bzr control
 
 
833
    takes_args = ['filename?']
 
 
835
    def run(self, filename=None):
 
 
836
        """Print the branch root."""
 
 
837
        b = Branch.open_containing(filename)[0]
 
 
841
class cmd_log(Command):
 
 
842
    """Show log of this branch.
 
 
844
    To request a range of logs, you can use the command -r begin..end
 
 
845
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
 
849
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
 
851
    takes_args = ['filename?']
 
 
852
    takes_options = [Option('forward', 
 
 
853
                            help='show from oldest to newest'),
 
 
854
                     'timezone', 'verbose', 
 
 
855
                     'show-ids', 'revision',
 
 
856
                     Option('line', help='format with one line per revision'),
 
 
859
                            help='show revisions whose message matches this regexp',
 
 
861
                     Option('short', help='use moderately short format'),
 
 
864
    def run(self, filename=None, timezone='original',
 
 
873
        from bzrlib.log import log_formatter, show_log
 
 
875
        assert message is None or isinstance(message, basestring), \
 
 
876
            "invalid message argument %r" % message
 
 
877
        direction = (forward and 'forward') or 'reverse'
 
 
880
            b, fp = Branch.open_containing(filename)
 
 
883
                    inv = b.working_tree().read_working_inventory()
 
 
884
                except NoWorkingTree:
 
 
885
                    inv = b.get_inventory(b.last_revision())
 
 
886
                file_id = inv.path2id(fp)
 
 
888
                file_id = None  # points to branch root
 
 
890
            b, relpath = Branch.open_containing('.')
 
 
896
        elif len(revision) == 1:
 
 
897
            rev1 = rev2 = revision[0].in_history(b).revno
 
 
898
        elif len(revision) == 2:
 
 
899
            rev1 = revision[0].in_history(b).revno
 
 
900
            rev2 = revision[1].in_history(b).revno
 
 
902
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
 
909
        mutter('encoding log as %r', bzrlib.user_encoding)
 
 
911
        # use 'replace' so that we don't abort if trying to write out
 
 
912
        # in e.g. the default C locale.
 
 
913
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
 
920
        lf = log_formatter(log_format,
 
 
923
                           show_timezone=timezone)
 
 
936
class cmd_touching_revisions(Command):
 
 
937
    """Return revision-ids which affected a particular file.
 
 
939
    A more user-friendly interface is "bzr log FILE"."""
 
 
941
    takes_args = ["filename"]
 
 
943
    def run(self, filename):
 
 
944
        b, relpath = Branch.open_containing(filename)[0]
 
 
945
        inv = b.working_tree().read_working_inventory()
 
 
946
        file_id = inv.path2id(relpath)
 
 
947
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
 
948
            print "%6d %s" % (revno, what)
 
 
951
class cmd_ls(Command):
 
 
952
    """List files in a tree.
 
 
954
    # TODO: Take a revision or remote path and list that tree instead.
 
 
956
    takes_options = ['verbose', 'revision',
 
 
957
                     Option('non-recursive',
 
 
958
                            help='don\'t recurse into sub-directories'),
 
 
960
                            help='Print all paths from the root of the branch.'),
 
 
961
                     Option('unknown', help='Print unknown files'),
 
 
962
                     Option('versioned', help='Print versioned files'),
 
 
963
                     Option('ignored', help='Print ignored files'),
 
 
965
                     Option('null', help='Null separate the files'),
 
 
968
    def run(self, revision=None, verbose=False, 
 
 
969
            non_recursive=False, from_root=False,
 
 
970
            unknown=False, versioned=False, ignored=False,
 
 
974
            raise BzrCommandError('Cannot set both --verbose and --null')
 
 
975
        all = not (unknown or versioned or ignored)
 
 
977
        selection = {'I':ignored, '?':unknown, 'V':versioned}
 
 
979
        b, relpath = Branch.open_containing('.')
 
 
985
            tree = b.working_tree()
 
 
987
            tree = b.revision_tree(revision[0].in_history(b).rev_id)
 
 
988
        for fp, fc, kind, fid, entry in tree.list_files():
 
 
989
            if fp.startswith(relpath):
 
 
990
                fp = fp[len(relpath):]
 
 
991
                if non_recursive and '/' in fp:
 
 
993
                if not all and not selection[fc]:
 
 
996
                    kindch = entry.kind_character()
 
 
997
                    print '%-8s %s%s' % (fc, fp, kindch)
 
 
1000
                    sys.stdout.write('\0')
 
 
1007
class cmd_unknowns(Command):
 
 
1008
    """List unknown files."""
 
 
1011
        from bzrlib.osutils import quotefn
 
 
1012
        for f in Branch.open_containing('.')[0].unknowns():
 
 
1017
class cmd_ignore(Command):
 
 
1018
    """Ignore a command or pattern.
 
 
1020
    To remove patterns from the ignore list, edit the .bzrignore file.
 
 
1022
    If the pattern contains a slash, it is compared to the whole path
 
 
1023
    from the branch root.  Otherwise, it is compared to only the last
 
 
1024
    component of the path.  To match a file only in the root directory,
 
 
1027
    Ignore patterns are case-insensitive on case-insensitive systems.
 
 
1029
    Note: wildcards must be quoted from the shell on Unix.
 
 
1032
        bzr ignore ./Makefile
 
 
1033
        bzr ignore '*.class'
 
 
1035
    # TODO: Complain if the filename is absolute
 
 
1036
    takes_args = ['name_pattern']
 
 
1038
    def run(self, name_pattern):
 
 
1039
        from bzrlib.atomicfile import AtomicFile
 
 
1042
        b, relpath = Branch.open_containing('.')
 
 
1043
        ifn = b.abspath('.bzrignore')
 
 
1045
        if os.path.exists(ifn):
 
 
1048
                igns = f.read().decode('utf-8')
 
 
1054
        # TODO: If the file already uses crlf-style termination, maybe
 
 
1055
        # we should use that for the newly added lines?
 
 
1057
        if igns and igns[-1] != '\n':
 
 
1059
        igns += name_pattern + '\n'
 
 
1062
            f = AtomicFile(ifn, 'wt')
 
 
1063
            f.write(igns.encode('utf-8'))
 
 
1068
        inv = b.working_tree().inventory
 
 
1069
        if inv.path2id('.bzrignore'):
 
 
1070
            mutter('.bzrignore is already versioned')
 
 
1072
            mutter('need to make new .bzrignore file versioned')
 
 
1073
            b.add(['.bzrignore'])
 
 
1077
class cmd_ignored(Command):
 
 
1078
    """List ignored files and the patterns that matched them.
 
 
1080
    See also: bzr ignore"""
 
 
1083
        tree = Branch.open_containing('.')[0].working_tree()
 
 
1084
        for path, file_class, kind, file_id, entry in tree.list_files():
 
 
1085
            if file_class != 'I':
 
 
1087
            ## XXX: Slightly inefficient since this was already calculated
 
 
1088
            pat = tree.is_ignored(path)
 
 
1089
            print '%-50s %s' % (path, pat)
 
 
1092
class cmd_lookup_revision(Command):
 
 
1093
    """Lookup the revision-id from a revision-number
 
 
1096
        bzr lookup-revision 33
 
 
1099
    takes_args = ['revno']
 
 
1102
    def run(self, revno):
 
 
1106
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
 
1108
        print Branch.open_containing('.')[0].get_rev_id(revno)
 
 
1111
class cmd_export(Command):
 
 
1112
    """Export past revision to destination directory.
 
 
1114
    If no revision is specified this exports the last committed revision.
 
 
1116
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
 
1117
    given, try to find the format with the extension. If no extension
 
 
1118
    is found exports to a directory (equivalent to --format=dir).
 
 
1120
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
 
1121
    is given, the top directory will be the root name of the file."""
 
 
1122
    # TODO: list known exporters
 
 
1123
    takes_args = ['dest']
 
 
1124
    takes_options = ['revision', 'format', 'root']
 
 
1125
    def run(self, dest, revision=None, format=None, root=None):
 
 
1127
        b = Branch.open_containing('.')[0]
 
 
1128
        if revision is None:
 
 
1129
            rev_id = b.last_revision()
 
 
1131
            if len(revision) != 1:
 
 
1132
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
 
1133
            rev_id = revision[0].in_history(b).rev_id
 
 
1134
        t = b.revision_tree(rev_id)
 
 
1135
        arg_root, ext = os.path.splitext(os.path.basename(dest))
 
 
1136
        if ext in ('.gz', '.bz2'):
 
 
1137
            new_root, new_ext = os.path.splitext(arg_root)
 
 
1138
            if new_ext == '.tar':
 
 
1144
            if ext in (".tar",):
 
 
1146
            elif ext in (".tar.gz", ".tgz"):
 
 
1148
            elif ext in (".tar.bz2", ".tbz2"):
 
 
1152
        t.export(dest, format, root)
 
 
1155
class cmd_cat(Command):
 
 
1156
    """Write a file's text from a previous revision."""
 
 
1158
    takes_options = ['revision']
 
 
1159
    takes_args = ['filename']
 
 
1162
    def run(self, filename, revision=None):
 
 
1163
        if revision is None:
 
 
1164
            raise BzrCommandError("bzr cat requires a revision number")
 
 
1165
        elif len(revision) != 1:
 
 
1166
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
 
1167
        b, relpath = Branch.open_containing(filename)
 
 
1168
        b.print_file(relpath, revision[0].in_history(b).revno)
 
 
1171
class cmd_local_time_offset(Command):
 
 
1172
    """Show the offset in seconds from GMT to local time."""
 
 
1176
        print bzrlib.osutils.local_time_offset()
 
 
1180
class cmd_commit(Command):
 
 
1181
    """Commit changes into a new revision.
 
 
1183
    If no arguments are given, the entire tree is committed.
 
 
1185
    If selected files are specified, only changes to those files are
 
 
1186
    committed.  If a directory is specified then the directory and everything 
 
 
1187
    within it is committed.
 
 
1189
    A selected-file commit may fail in some cases where the committed
 
 
1190
    tree would be invalid, such as trying to commit a file in a
 
 
1191
    newly-added directory that is not itself committed.
 
 
1193
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
 
1195
    # TODO: Strict commit that fails if there are deleted files.
 
 
1196
    #       (what does "deleted files" mean ??)
 
 
1198
    # TODO: Give better message for -s, --summary, used by tla people
 
 
1200
    # XXX: verbose currently does nothing
 
 
1202
    takes_args = ['selected*']
 
 
1203
    takes_options = ['message', 'verbose', 
 
 
1205
                            help='commit even if nothing has changed'),
 
 
1206
                     Option('file', type=str, 
 
 
1208
                            help='file containing commit message'),
 
 
1210
                            help="refuse to commit if there are unknown "
 
 
1211
                            "files in the working tree."),
 
 
1213
    aliases = ['ci', 'checkin']
 
 
1215
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
 
1216
            unchanged=False, strict=False):
 
 
1217
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
 
 
1219
        from bzrlib.msgeditor import edit_commit_message
 
 
1220
        from bzrlib.status import show_status
 
 
1221
        from cStringIO import StringIO
 
 
1223
        b, selected_list = branch_files(selected_list)
 
 
1224
        if message is None and not file:
 
 
1225
            catcher = StringIO()
 
 
1226
            show_status(b, specific_files=selected_list,
 
 
1228
            message = edit_commit_message(catcher.getvalue())
 
 
1231
                raise BzrCommandError("please specify a commit message"
 
 
1232
                                      " with either --message or --file")
 
 
1233
        elif message and file:
 
 
1234
            raise BzrCommandError("please specify either --message or --file")
 
 
1238
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
 
1241
                raise BzrCommandError("empty commit message specified")
 
 
1244
            b.working_tree().commit(message, specific_files=selected_list,
 
 
1245
                     allow_pointless=unchanged, strict=strict)
 
 
1246
        except PointlessCommit:
 
 
1247
            # FIXME: This should really happen before the file is read in;
 
 
1248
            # perhaps prepare the commit; get the message; then actually commit
 
 
1249
            raise BzrCommandError("no changes to commit",
 
 
1250
                                  ["use --unchanged to commit anyhow"])
 
 
1251
        except ConflictsInTree:
 
 
1252
            raise BzrCommandError("Conflicts detected in working tree.  "
 
 
1253
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
 
 
1254
        except StrictCommitFailed:
 
 
1255
            raise BzrCommandError("Commit refused because there are unknown "
 
 
1256
                                  "files in the working tree.")
 
 
1259
class cmd_check(Command):
 
 
1260
    """Validate consistency of branch history.
 
 
1262
    This command checks various invariants about the branch storage to
 
 
1263
    detect data corruption or bzr bugs.
 
 
1265
    takes_args = ['dir?']
 
 
1266
    takes_options = ['verbose']
 
 
1268
    def run(self, dir='.', verbose=False):
 
 
1269
        from bzrlib.check import check
 
 
1270
        check(Branch.open_containing(dir)[0], verbose)
 
 
1273
class cmd_scan_cache(Command):
 
 
1276
        from bzrlib.hashcache import HashCache
 
 
1282
        print '%6d stats' % c.stat_count
 
 
1283
        print '%6d in hashcache' % len(c._cache)
 
 
1284
        print '%6d files removed from cache' % c.removed_count
 
 
1285
        print '%6d hashes updated' % c.update_count
 
 
1286
        print '%6d files changed too recently to cache' % c.danger_count
 
 
1293
class cmd_upgrade(Command):
 
 
1294
    """Upgrade branch storage to current format.
 
 
1296
    The check command or bzr developers may sometimes advise you to run
 
 
1299
    This version of this command upgrades from the full-text storage
 
 
1300
    used by bzr 0.0.8 and earlier to the weave format (v5).
 
 
1302
    takes_args = ['dir?']
 
 
1304
    def run(self, dir='.'):
 
 
1305
        from bzrlib.upgrade import upgrade
 
 
1309
class cmd_whoami(Command):
 
 
1310
    """Show bzr user id."""
 
 
1311
    takes_options = ['email']
 
 
1314
    def run(self, email=False):
 
 
1316
            b = bzrlib.branch.Branch.open_containing('.')[0]
 
 
1317
            config = bzrlib.config.BranchConfig(b)
 
 
1318
        except NotBranchError:
 
 
1319
            config = bzrlib.config.GlobalConfig()
 
 
1322
            print config.user_email()
 
 
1324
            print config.username()
 
 
1326
class cmd_nick(Command):
 
 
1328
    Print or set the branch nickname.  
 
 
1329
    If unset, the tree root directory name is used as the nickname
 
 
1330
    To print the current nickname, execute with no argument.  
 
 
1332
    takes_args = ['nickname?']
 
 
1333
    def run(self, nickname=None):
 
 
1334
        branch = Branch.open_containing('.')[0]
 
 
1335
        if nickname is None:
 
 
1336
            self.printme(branch)
 
 
1338
            branch.nick = nickname
 
 
1341
    def printme(self, branch):
 
 
1344
class cmd_selftest(Command):
 
 
1345
    """Run internal test suite.
 
 
1347
    This creates temporary test directories in the working directory,
 
 
1348
    but not existing data is affected.  These directories are deleted
 
 
1349
    if the tests pass, or left behind to help in debugging if they
 
 
1350
    fail and --keep-output is specified.
 
 
1352
    If arguments are given, they are regular expressions that say
 
 
1353
    which tests should run.
 
 
1355
    # TODO: --list should give a list of all available tests
 
 
1357
    takes_args = ['testspecs*']
 
 
1358
    takes_options = ['verbose', 
 
 
1359
                     Option('one', help='stop when one test fails'),
 
 
1360
                     Option('keep-output', 
 
 
1361
                            help='keep output directories when tests fail')
 
 
1364
    def run(self, testspecs_list=None, verbose=False, one=False,
 
 
1367
        from bzrlib.selftest import selftest
 
 
1368
        # we don't want progress meters from the tests to go to the
 
 
1369
        # real output; and we don't want log messages cluttering up
 
 
1371
        save_ui = bzrlib.ui.ui_factory
 
 
1372
        bzrlib.trace.info('running tests...')
 
 
1374
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
 
1375
            if testspecs_list is not None:
 
 
1376
                pattern = '|'.join(testspecs_list)
 
 
1379
            result = selftest(verbose=verbose, 
 
 
1381
                              stop_on_failure=one, 
 
 
1382
                              keep_output=keep_output)
 
 
1384
                bzrlib.trace.info('tests passed')
 
 
1386
                bzrlib.trace.info('tests failed')
 
 
1387
            return int(not result)
 
 
1389
            bzrlib.ui.ui_factory = save_ui
 
 
1393
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
 
1394
    # is bzrlib itself in a branch?
 
 
1395
    bzrrev = bzrlib.get_bzr_revision()
 
 
1397
        print "  (bzr checkout, revision %d {%s})" % bzrrev
 
 
1398
    print bzrlib.__copyright__
 
 
1399
    print "http://bazaar-ng.org/"
 
 
1401
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
 
1402
    print "you may use, modify and redistribute it under the terms of the GNU"
 
 
1403
    print "General Public License version 2 or later."
 
 
1406
class cmd_version(Command):
 
 
1407
    """Show version of bzr."""
 
 
1412
class cmd_rocks(Command):
 
 
1413
    """Statement of optimism."""
 
 
1417
        print "it sure does!"
 
 
1420
class cmd_find_merge_base(Command):
 
 
1421
    """Find and print a base revision for merging two branches.
 
 
1423
    # TODO: Options to specify revisions on either side, as if
 
 
1424
    #       merging only part of the history.
 
 
1425
    takes_args = ['branch', 'other']
 
 
1429
    def run(self, branch, other):
 
 
1430
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
 
 
1432
        branch1 = Branch.open_containing(branch)[0]
 
 
1433
        branch2 = Branch.open_containing(other)[0]
 
 
1435
        history_1 = branch1.revision_history()
 
 
1436
        history_2 = branch2.revision_history()
 
 
1438
        last1 = branch1.last_revision()
 
 
1439
        last2 = branch2.last_revision()
 
 
1441
        source = MultipleRevisionSources(branch1, branch2)
 
 
1443
        base_rev_id = common_ancestor(last1, last2, source)
 
 
1445
        print 'merge base is revision %s' % base_rev_id
 
 
1449
        if base_revno is None:
 
 
1450
            raise bzrlib.errors.UnrelatedBranches()
 
 
1452
        print ' r%-6d in %s' % (base_revno, branch)
 
 
1454
        other_revno = branch2.revision_id_to_revno(base_revid)
 
 
1456
        print ' r%-6d in %s' % (other_revno, other)
 
 
1460
class cmd_merge(Command):
 
 
1461
    """Perform a three-way merge.
 
 
1463
    The branch is the branch you will merge from.  By default, it will
 
 
1464
    merge the latest revision.  If you specify a revision, that
 
 
1465
    revision will be merged.  If you specify two revisions, the first
 
 
1466
    will be used as a BASE, and the second one as OTHER.  Revision
 
 
1467
    numbers are always relative to the specified branch.
 
 
1469
    By default bzr will try to merge in all new work from the other
 
 
1470
    branch, automatically determining an appropriate base.  If this
 
 
1471
    fails, you may need to give an explicit base.
 
 
1475
    To merge the latest revision from bzr.dev
 
 
1476
    bzr merge ../bzr.dev
 
 
1478
    To merge changes up to and including revision 82 from bzr.dev
 
 
1479
    bzr merge -r 82 ../bzr.dev
 
 
1481
    To merge the changes introduced by 82, without previous changes:
 
 
1482
    bzr merge -r 81..82 ../bzr.dev
 
 
1484
    merge refuses to run if there are any uncommitted changes, unless
 
 
1487
    takes_args = ['branch?']
 
 
1488
    takes_options = ['revision', 'force', 'merge-type', 'reprocess',
 
 
1489
                     Option('show-base', help="Show base revision text in "
 
 
1492
    def run(self, branch=None, revision=None, force=False, merge_type=None,
 
 
1493
            show_base=False, reprocess=False):
 
 
1494
        from bzrlib.merge import merge
 
 
1495
        from bzrlib.merge_core import ApplyMerge3
 
 
1496
        if merge_type is None:
 
 
1497
            merge_type = ApplyMerge3
 
 
1499
            branch = Branch.open_containing('.')[0].get_parent()
 
 
1501
                raise BzrCommandError("No merge location known or specified.")
 
 
1503
                print "Using saved location: %s" % branch 
 
 
1504
        if revision is None or len(revision) < 1:
 
 
1506
            other = [branch, -1]
 
 
1508
            if len(revision) == 1:
 
 
1510
                other_branch = Branch.open_containing(branch)[0]
 
 
1511
                revno = revision[0].in_history(other_branch).revno
 
 
1512
                other = [branch, revno]
 
 
1514
                assert len(revision) == 2
 
 
1515
                if None in revision:
 
 
1516
                    raise BzrCommandError(
 
 
1517
                        "Merge doesn't permit that revision specifier.")
 
 
1518
                b = Branch.open_containing(branch)[0]
 
 
1520
                base = [branch, revision[0].in_history(b).revno]
 
 
1521
                other = [branch, revision[1].in_history(b).revno]
 
 
1524
            conflict_count = merge(other, base, check_clean=(not force),
 
 
1525
                                   merge_type=merge_type, reprocess=reprocess,
 
 
1526
                                   show_base=show_base)
 
 
1527
            if conflict_count != 0:
 
 
1531
        except bzrlib.errors.AmbiguousBase, e:
 
 
1532
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
 
1533
                 "candidates are:\n  "
 
 
1534
                 + "\n  ".join(e.bases)
 
 
1536
                 "please specify an explicit base with -r,\n"
 
 
1537
                 "and (if you want) report this to the bzr developers\n")
 
 
1541
class cmd_remerge(Command):
 
 
1544
    takes_args = ['file*']
 
 
1545
    takes_options = ['merge-type', 'reprocess',
 
 
1546
                     Option('show-base', help="Show base revision text in "
 
 
1549
    def run(self, file_list=None, merge_type=None, show_base=False,
 
 
1551
        from bzrlib.merge import merge_inner, transform_tree
 
 
1552
        from bzrlib.merge_core import ApplyMerge3
 
 
1553
        if merge_type is None:
 
 
1554
            merge_type = ApplyMerge3
 
 
1555
        b, file_list = branch_files(file_list)
 
 
1558
            pending_merges = b.working_tree().pending_merges() 
 
 
1559
            if len(pending_merges) != 1:
 
 
1560
                raise BzrCommandError("Sorry, remerge only works after normal"
 
 
1561
                                      + " merges.  Not cherrypicking or"
 
 
1563
            this_tree = b.working_tree()
 
 
1564
            base_revision = common_ancestor(b.last_revision(), 
 
 
1565
                                            pending_merges[0], b)
 
 
1566
            base_tree = b.revision_tree(base_revision)
 
 
1567
            other_tree = b.revision_tree(pending_merges[0])
 
 
1568
            interesting_ids = None
 
 
1569
            if file_list is not None:
 
 
1570
                interesting_ids = set()
 
 
1571
                for filename in file_list:
 
 
1572
                    file_id = this_tree.path2id(filename)
 
 
1573
                    interesting_ids.add(file_id)
 
 
1574
                    if this_tree.kind(file_id) != "directory":
 
 
1577
                    for name, ie in this_tree.inventory.iter_entries(file_id):
 
 
1578
                        interesting_ids.add(ie.file_id)
 
 
1579
            transform_tree(this_tree, b.basis_tree(), interesting_ids)
 
 
1580
            if file_list is None:
 
 
1581
                restore_files = list(this_tree.iter_conflicts())
 
 
1583
                restore_files = file_list
 
 
1584
            for filename in restore_files:
 
 
1586
                    restore(this_tree.abspath(filename))
 
 
1587
                except NotConflicted:
 
 
1589
            conflicts =  merge_inner(b, other_tree, base_tree, 
 
 
1590
                                     interesting_ids = interesting_ids, 
 
 
1591
                                     other_rev_id=pending_merges[0], 
 
 
1592
                                     merge_type=merge_type, 
 
 
1593
                                     show_base=show_base,
 
 
1594
                                     reprocess=reprocess)
 
 
1602
class cmd_revert(Command):
 
 
1603
    """Reverse all changes since the last commit.
 
 
1605
    Only versioned files are affected.  Specify filenames to revert only 
 
 
1606
    those files.  By default, any files that are changed will be backed up
 
 
1607
    first.  Backup files have a '~' appended to their name.
 
 
1609
    takes_options = ['revision', 'no-backup']
 
 
1610
    takes_args = ['file*']
 
 
1611
    aliases = ['merge-revert']
 
 
1613
    def run(self, revision=None, no_backup=False, file_list=None):
 
 
1614
        from bzrlib.merge import merge_inner
 
 
1615
        from bzrlib.commands import parse_spec
 
 
1616
        if file_list is not None:
 
 
1617
            if len(file_list) == 0:
 
 
1618
                raise BzrCommandError("No files specified")
 
 
1621
        if revision is None:
 
 
1623
            b = Branch.open_containing('.')[0]
 
 
1624
            rev_id = b.last_revision()
 
 
1625
        elif len(revision) != 1:
 
 
1626
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
 
1628
            b, file_list = branch_files(file_list)
 
 
1629
            rev_id = revision[0].in_history(b).rev_id
 
 
1630
        b.working_tree().revert(file_list, b.revision_tree(rev_id),
 
 
1634
class cmd_assert_fail(Command):
 
 
1635
    """Test reporting of assertion failures"""
 
 
1638
        assert False, "always fails"
 
 
1641
class cmd_help(Command):
 
 
1642
    """Show help on a command or other topic.
 
 
1644
    For a list of all available commands, say 'bzr help commands'."""
 
 
1645
    takes_options = ['long']
 
 
1646
    takes_args = ['topic?']
 
 
1650
    def run(self, topic=None, long=False):
 
 
1652
        if topic is None and long:
 
 
1657
class cmd_shell_complete(Command):
 
 
1658
    """Show appropriate completions for context.
 
 
1660
    For a list of all available commands, say 'bzr shell-complete'."""
 
 
1661
    takes_args = ['context?']
 
 
1666
    def run(self, context=None):
 
 
1667
        import shellcomplete
 
 
1668
        shellcomplete.shellcomplete(context)
 
 
1671
class cmd_fetch(Command):
 
 
1672
    """Copy in history from another branch but don't merge it.
 
 
1674
    This is an internal method used for pull and merge."""
 
 
1676
    takes_args = ['from_branch', 'to_branch']
 
 
1677
    def run(self, from_branch, to_branch):
 
 
1678
        from bzrlib.fetch import Fetcher
 
 
1679
        from bzrlib.branch import Branch
 
 
1680
        from_b = Branch.open(from_branch)
 
 
1681
        to_b = Branch.open(to_branch)
 
 
1686
                Fetcher(to_b, from_b)
 
 
1693
class cmd_missing(Command):
 
 
1694
    """What is missing in this branch relative to other branch.
 
 
1696
    # TODO: rewrite this in terms of ancestry so that it shows only
 
 
1699
    takes_args = ['remote?']
 
 
1700
    aliases = ['mis', 'miss']
 
 
1701
    # We don't have to add quiet to the list, because 
 
 
1702
    # unknown options are parsed as booleans
 
 
1703
    takes_options = ['verbose', 'quiet']
 
 
1706
    def run(self, remote=None, verbose=False, quiet=False):
 
 
1707
        from bzrlib.errors import BzrCommandError
 
 
1708
        from bzrlib.missing import show_missing
 
 
1710
        if verbose and quiet:
 
 
1711
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
 
1713
        b = Branch.open_containing('.')[0]
 
 
1714
        parent = b.get_parent()
 
 
1717
                raise BzrCommandError("No missing location known or specified.")
 
 
1720
                    print "Using last location: %s" % parent
 
 
1722
        elif parent is None:
 
 
1723
            # We only update parent if it did not exist, missing
 
 
1724
            # should not change the parent
 
 
1725
            b.set_parent(remote)
 
 
1726
        br_remote = Branch.open_containing(remote)[0]
 
 
1727
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
 
1730
class cmd_plugins(Command):
 
 
1735
        import bzrlib.plugin
 
 
1736
        from inspect import getdoc
 
 
1737
        for plugin in bzrlib.plugin.all_plugins:
 
 
1738
            if hasattr(plugin, '__path__'):
 
 
1739
                print plugin.__path__[0]
 
 
1740
            elif hasattr(plugin, '__file__'):
 
 
1741
                print plugin.__file__
 
 
1747
                print '\t', d.split('\n')[0]
 
 
1750
class cmd_testament(Command):
 
 
1751
    """Show testament (signing-form) of a revision."""
 
 
1752
    takes_options = ['revision', 'long']
 
 
1753
    takes_args = ['branch?']
 
 
1755
    def run(self, branch='.', revision=None, long=False):
 
 
1756
        from bzrlib.testament import Testament
 
 
1757
        b = Branch.open_containing(branch)[0]
 
 
1760
            if revision is None:
 
 
1761
                rev_id = b.last_revision()
 
 
1763
                rev_id = revision[0].in_history(b).rev_id
 
 
1764
            t = Testament.from_revision(b, rev_id)
 
 
1766
                sys.stdout.writelines(t.as_text_lines())
 
 
1768
                sys.stdout.write(t.as_short_text())
 
 
1773
class cmd_annotate(Command):
 
 
1774
    """Show the origin of each line in a file.
 
 
1776
    This prints out the given file with an annotation on the left side
 
 
1777
    indicating which revision, author and date introduced the change.
 
 
1779
    If the origin is the same for a run of consecutive lines, it is 
 
 
1780
    shown only at the top, unless the --all option is given.
 
 
1782
    # TODO: annotate directories; showing when each file was last changed
 
 
1783
    # TODO: annotate a previous version of a file
 
 
1784
    # TODO: if the working copy is modified, show annotations on that 
 
 
1785
    #       with new uncommitted lines marked
 
 
1786
    aliases = ['blame', 'praise']
 
 
1787
    takes_args = ['filename']
 
 
1788
    takes_options = [Option('all', help='show annotations on all lines'),
 
 
1789
                     Option('long', help='show date in annotations'),
 
 
1793
    def run(self, filename, all=False, long=False):
 
 
1794
        from bzrlib.annotate import annotate_file
 
 
1795
        b, relpath = Branch.open_containing(filename)
 
 
1798
            tree = WorkingTree(b.base, b)
 
 
1799
            tree = b.revision_tree(b.last_revision())
 
 
1800
            file_id = tree.inventory.path2id(relpath)
 
 
1801
            file_version = tree.inventory[file_id].revision
 
 
1802
            annotate_file(b, file_version, file_id, long, all, sys.stdout)
 
 
1807
class cmd_re_sign(Command):
 
 
1808
    """Create a digital signature for an existing revision."""
 
 
1809
    # TODO be able to replace existing ones.
 
 
1811
    hidden = True # is this right ?
 
 
1812
    takes_args = ['revision_id?']
 
 
1813
    takes_options = ['revision']
 
 
1815
    def run(self, revision_id=None, revision=None):
 
 
1816
        import bzrlib.config as config
 
 
1817
        import bzrlib.gpg as gpg
 
 
1818
        if revision_id is not None and revision is not None:
 
 
1819
            raise BzrCommandError('You can only supply one of revision_id or --revision')
 
 
1820
        if revision_id is None and revision is None:
 
 
1821
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
 
1822
        b = Branch.open_containing('.')[0]
 
 
1823
        gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
 
 
1824
        if revision_id is not None:
 
 
1825
            b.sign_revision(revision_id, gpg_strategy)
 
 
1826
        elif revision is not None:
 
 
1827
            if len(revision) == 1:
 
 
1828
                revno, rev_id = revision[0].in_history(b)
 
 
1829
                b.sign_revision(rev_id, gpg_strategy)
 
 
1830
            elif len(revision) == 2:
 
 
1831
                # are they both on rh- if so we can walk between them
 
 
1832
                # might be nice to have a range helper for arbitrary
 
 
1833
                # revision paths. hmm.
 
 
1834
                from_revno, from_revid = revision[0].in_history(b)
 
 
1835
                to_revno, to_revid = revision[1].in_history(b)
 
 
1836
                if to_revid is None:
 
 
1837
                    to_revno = b.revno()
 
 
1838
                if from_revno is None or to_revno is None:
 
 
1839
                    raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
 
 
1840
                for revno in range(from_revno, to_revno + 1):
 
 
1841
                    b.sign_revision(b.get_rev_id(revno), gpg_strategy)
 
 
1843
                raise BzrCommandError('Please supply either one revision, or a range.')
 
 
1846
# these get imported and then picked up by the scan for cmd_*
 
 
1847
# TODO: Some more consistent way to split command definitions across files;
 
 
1848
# we do need to load at least some information about them to know of 
 
 
1850
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore