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
 
 
23
from bzrlib.trace import mutter, note, log_error, warning
 
 
24
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
 
25
from bzrlib.branch import find_branch
 
 
26
from bzrlib import BZRDIR
 
 
27
from bzrlib.commands import Command
 
 
30
class cmd_status(Command):
 
 
31
    """Display status summary.
 
 
33
    This reports on versioned and unknown files, reporting them
 
 
34
    grouped by state.  Possible states are:
 
 
37
        Versioned in the working copy but not in the previous revision.
 
 
40
        Versioned in the previous revision but removed or deleted
 
 
44
        Path of this file changed from the previous revision;
 
 
45
        the text may also have changed.  This includes files whose
 
 
46
        parent directory was renamed.
 
 
49
        Text has changed since the previous revision.
 
 
52
        Nothing about this file has changed since the previous revision.
 
 
53
        Only shown with --all.
 
 
56
        Not versioned and not matching an ignore pattern.
 
 
58
    To see ignored files use 'bzr ignored'.  For details in the
 
 
59
    changes to file texts, use 'bzr diff'.
 
 
61
    If no arguments are specified, the status of the entire working
 
 
62
    directory is shown.  Otherwise, only the status of the specified
 
 
63
    files or directories is reported.  If a directory is given, status
 
 
64
    is reported for everything inside that directory.
 
 
66
    If a revision is specified, the changes since that revision are shown.
 
 
68
    takes_args = ['file*']
 
 
69
    takes_options = ['all', 'show-ids', 'revision']
 
 
70
    aliases = ['st', 'stat']
 
 
72
    def run(self, all=False, show_ids=False, file_list=None):
 
 
74
            b = find_branch(file_list[0])
 
 
75
            file_list = [b.relpath(x) for x in file_list]
 
 
76
            # special case: only one path was given and it's the root
 
 
83
        from bzrlib.status import show_status
 
 
84
        show_status(b, show_unchanged=all, show_ids=show_ids,
 
 
85
                    specific_files=file_list)
 
 
88
class cmd_cat_revision(Command):
 
 
89
    """Write out metadata for a revision."""
 
 
92
    takes_args = ['revision_id']
 
 
94
    def run(self, revision_id):
 
 
96
        sys.stdout.write(b.get_revision_xml_file(revision_id).read())
 
 
99
class cmd_revno(Command):
 
 
100
    """Show current revision number.
 
 
102
    This is equal to the number of revisions on this branch."""
 
 
104
        print find_branch('.').revno()
 
 
107
class cmd_revision_info(Command):
 
 
108
    """Show revision number and revision id for a given revision identifier.
 
 
111
    takes_args = ['revision_info*']
 
 
112
    takes_options = ['revision']
 
 
113
    def run(self, revision=None, revision_info_list=None):
 
 
114
        from bzrlib.branch import find_branch
 
 
117
        if revision is not None:
 
 
118
            revs.extend(revision)
 
 
119
        if revision_info_list is not None:
 
 
120
            revs.extend(revision_info_list)
 
 
122
            raise BzrCommandError('You must supply a revision identifier')
 
 
127
            print '%4d %s' % b.get_revision_info(rev)
 
 
130
class cmd_add(Command):
 
 
131
    """Add specified files or directories.
 
 
133
    In non-recursive mode, all the named items are added, regardless
 
 
134
    of whether they were previously ignored.  A warning is given if
 
 
135
    any of the named files are already versioned.
 
 
137
    In recursive mode (the default), files are treated the same way
 
 
138
    but the behaviour for directories is different.  Directories that
 
 
139
    are already versioned do not give a warning.  All directories,
 
 
140
    whether already versioned or not, are searched for files or
 
 
141
    subdirectories that are neither versioned or ignored, and these
 
 
142
    are added.  This search proceeds recursively into versioned
 
 
143
    directories.  If no names are given '.' is assumed.
 
 
145
    Therefore simply saying 'bzr add' will version all files that
 
 
146
    are currently unknown.
 
 
148
    TODO: Perhaps adding a file whose directly is not versioned should
 
 
149
    recursively add that parent, rather than giving an error?
 
 
151
    takes_args = ['file*']
 
 
152
    takes_options = ['verbose', 'no-recurse']
 
 
154
    def run(self, file_list, verbose=False, no_recurse=False):
 
 
155
        # verbose currently has no effect
 
 
156
        from bzrlib.add import smart_add, add_reporter_print
 
 
157
        smart_add(file_list, not no_recurse, add_reporter_print)
 
 
161
class cmd_mkdir(Command):
 
 
162
    """Create a new versioned directory.
 
 
164
    This is equivalent to creating the directory and then adding it.
 
 
166
    takes_args = ['dir+']
 
 
168
    def run(self, dir_list):
 
 
179
class cmd_relpath(Command):
 
 
180
    """Show path of a file relative to root"""
 
 
181
    takes_args = ['filename']
 
 
184
    def run(self, filename):
 
 
185
        print find_branch(filename).relpath(filename)
 
 
189
class cmd_inventory(Command):
 
 
190
    """Show inventory of the current working copy or a revision."""
 
 
191
    takes_options = ['revision', 'show-ids']
 
 
193
    def run(self, revision=None, show_ids=False):
 
 
196
            inv = b.read_working_inventory()
 
 
198
            if len(revision) > 1:
 
 
199
                raise BzrCommandError('bzr inventory --revision takes'
 
 
200
                    ' exactly one revision identifier')
 
 
201
            inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
 
 
203
        for path, entry in inv.entries():
 
 
205
                print '%-50s %s' % (path, entry.file_id)
 
 
210
class cmd_move(Command):
 
 
211
    """Move files to a different directory.
 
 
216
    The destination must be a versioned directory in the same branch.
 
 
218
    takes_args = ['source$', 'dest']
 
 
219
    def run(self, source_list, dest):
 
 
222
        # TODO: glob expansion on windows?
 
 
223
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
 
 
226
class cmd_rename(Command):
 
 
227
    """Change the name of an entry.
 
 
230
      bzr rename frob.c frobber.c
 
 
231
      bzr rename src/frob.c lib/frob.c
 
 
233
    It is an error if the destination name exists.
 
 
235
    See also the 'move' command, which moves files into a different
 
 
236
    directory without changing their name.
 
 
238
    TODO: Some way to rename multiple files without invoking bzr for each
 
 
240
    takes_args = ['from_name', 'to_name']
 
 
242
    def run(self, from_name, to_name):
 
 
244
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
 
 
248
class cmd_mv(Command):
 
 
249
    """Move or rename a file.
 
 
252
        bzr mv OLDNAME NEWNAME
 
 
253
        bzr mv SOURCE... DESTINATION
 
 
255
    If the last argument is a versioned directory, all the other names
 
 
256
    are moved into it.  Otherwise, there must be exactly two arguments
 
 
257
    and the file is changed to a new name, which must not already exist.
 
 
259
    Files cannot be moved between branches.
 
 
261
    takes_args = ['names*']
 
 
262
    def run(self, names_list):
 
 
263
        if len(names_list) < 2:
 
 
264
            raise BzrCommandError("missing file argument")
 
 
265
        b = find_branch(names_list[0])
 
 
267
        rel_names = [b.relpath(x) for x in names_list]
 
 
269
        if os.path.isdir(names_list[-1]):
 
 
270
            # move into existing directory
 
 
271
            for pair in b.move(rel_names[:-1], rel_names[-1]):
 
 
272
                print "%s => %s" % pair
 
 
274
            if len(names_list) != 2:
 
 
275
                raise BzrCommandError('to mv multiple files the destination '
 
 
276
                                      'must be a versioned directory')
 
 
277
            for pair in b.move(rel_names[0], rel_names[1]):
 
 
278
                print "%s => %s" % pair
 
 
283
class cmd_pull(Command):
 
 
284
    """Pull any changes from another branch into the current one.
 
 
286
    If the location is omitted, the last-used location will be used.
 
 
287
    Both the revision history and the working directory will be
 
 
290
    This command only works on branches that have not diverged.  Branches are
 
 
291
    considered diverged if both branches have had commits without first
 
 
292
    pulling from the other.
 
 
294
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
 
295
    from one into the other.
 
 
297
    takes_args = ['location?']
 
 
299
    def run(self, location=None):
 
 
300
        from bzrlib.merge import merge
 
 
302
        from shutil import rmtree
 
 
304
        from bzrlib.branch import pull_loc
 
 
306
        br_to = find_branch('.')
 
 
309
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
 
 
311
            if e.errno != errno.ENOENT:
 
 
314
            if stored_loc is None:
 
 
315
                raise BzrCommandError("No pull location known or specified.")
 
 
317
                print "Using last location: %s" % stored_loc
 
 
318
                location = stored_loc
 
 
319
        cache_root = tempfile.mkdtemp()
 
 
320
        from bzrlib.branch import DivergedBranches
 
 
321
        br_from = find_branch(location)
 
 
322
        location = pull_loc(br_from)
 
 
323
        old_revno = br_to.revno()
 
 
325
            from branch import find_cached_branch, DivergedBranches
 
 
326
            br_from = find_cached_branch(location, cache_root)
 
 
327
            location = pull_loc(br_from)
 
 
328
            old_revno = br_to.revno()
 
 
330
                br_to.update_revisions(br_from)
 
 
331
            except DivergedBranches:
 
 
332
                raise BzrCommandError("These branches have diverged."
 
 
335
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
 
336
            if location != stored_loc:
 
 
337
                br_to.controlfile("x-pull", "wb").write(location + "\n")
 
 
343
class cmd_branch(Command):
 
 
344
    """Create a new copy of a branch.
 
 
346
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
 
347
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
 
349
    To retrieve the branch as of a particular revision, supply the --revision
 
 
350
    parameter, as in "branch foo/bar -r 5".
 
 
352
    takes_args = ['from_location', 'to_location?']
 
 
353
    takes_options = ['revision']
 
 
354
    aliases = ['get', 'clone']
 
 
356
    def run(self, from_location, to_location=None, revision=None):
 
 
357
        from bzrlib.branch import copy_branch, find_cached_branch
 
 
360
        from shutil import rmtree
 
 
361
        cache_root = tempfile.mkdtemp()
 
 
365
            elif len(revision) > 1:
 
 
366
                raise BzrCommandError(
 
 
367
                    'bzr branch --revision takes exactly 1 revision value')
 
 
369
                br_from = find_cached_branch(from_location, cache_root)
 
 
371
                if e.errno == errno.ENOENT:
 
 
372
                    raise BzrCommandError('Source location "%s" does not'
 
 
373
                                          ' exist.' % to_location)
 
 
376
            if to_location is None:
 
 
377
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
 
379
                os.mkdir(to_location)
 
 
381
                if e.errno == errno.EEXIST:
 
 
382
                    raise BzrCommandError('Target directory "%s" already'
 
 
383
                                          ' exists.' % to_location)
 
 
384
                if e.errno == errno.ENOENT:
 
 
385
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
 
390
                copy_branch(br_from, to_location, revision[0])
 
 
391
            except bzrlib.errors.NoSuchRevision:
 
 
393
                msg = "The branch %s has no revision %d." % (from_location, revision[0])
 
 
394
                raise BzrCommandError(msg)
 
 
399
class cmd_renames(Command):
 
 
400
    """Show list of renamed files.
 
 
402
    TODO: Option to show renames between two historical versions.
 
 
404
    TODO: Only show renames under dir, rather than in the whole branch.
 
 
406
    takes_args = ['dir?']
 
 
408
    def run(self, dir='.'):
 
 
410
        old_inv = b.basis_tree().inventory
 
 
411
        new_inv = b.read_working_inventory()
 
 
413
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
 
415
        for old_name, new_name in renames:
 
 
416
            print "%s => %s" % (old_name, new_name)        
 
 
419
class cmd_info(Command):
 
 
420
    """Show statistical information about a branch."""
 
 
421
    takes_args = ['branch?']
 
 
423
    def run(self, branch=None):
 
 
426
        b = find_branch(branch)
 
 
430
class cmd_remove(Command):
 
 
431
    """Make a file unversioned.
 
 
433
    This makes bzr stop tracking changes to a versioned file.  It does
 
 
434
    not delete the working copy.
 
 
436
    takes_args = ['file+']
 
 
437
    takes_options = ['verbose']
 
 
439
    def run(self, file_list, verbose=False):
 
 
440
        b = find_branch(file_list[0])
 
 
441
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
 
 
444
class cmd_file_id(Command):
 
 
445
    """Print file_id of a particular file or directory.
 
 
447
    The file_id is assigned when the file is first added and remains the
 
 
448
    same through all revisions where the file exists, even when it is
 
 
452
    takes_args = ['filename']
 
 
453
    def run(self, filename):
 
 
454
        b = find_branch(filename)
 
 
455
        i = b.inventory.path2id(b.relpath(filename))
 
 
457
            raise BzrError("%r is not a versioned file" % filename)
 
 
462
class cmd_file_path(Command):
 
 
463
    """Print path of file_ids to a file or directory.
 
 
465
    This prints one line for each directory down to the target,
 
 
466
    starting at the branch root."""
 
 
468
    takes_args = ['filename']
 
 
469
    def run(self, filename):
 
 
470
        b = find_branch(filename)
 
 
472
        fid = inv.path2id(b.relpath(filename))
 
 
474
            raise BzrError("%r is not a versioned file" % filename)
 
 
475
        for fip in inv.get_idpath(fid):
 
 
479
class cmd_revision_history(Command):
 
 
480
    """Display list of revision ids on this branch."""
 
 
483
        for patchid in find_branch('.').revision_history():
 
 
487
class cmd_ancestry(Command):
 
 
488
    """List all revisions merged into this branch."""
 
 
492
        for revision_id in b.get_ancestry(b.last_patch()):
 
 
496
class cmd_directories(Command):
 
 
497
    """Display list of versioned directories in this branch."""
 
 
499
        for name, ie in find_branch('.').read_working_inventory().directories():
 
 
506
class cmd_init(Command):
 
 
507
    """Make a directory into a versioned branch.
 
 
509
    Use this to create an empty branch, or before importing an
 
 
512
    Recipe for importing a tree of files:
 
 
517
        bzr commit -m 'imported project'
 
 
520
        from bzrlib.branch import Branch
 
 
521
        Branch('.', init=True)
 
 
524
class cmd_diff(Command):
 
 
525
    """Show differences in working tree.
 
 
527
    If files are listed, only the changes in those files are listed.
 
 
528
    Otherwise, all changes for the tree are listed.
 
 
530
    TODO: Allow diff across branches.
 
 
532
    TODO: Option to use external diff command; could be GNU diff, wdiff,
 
 
535
    TODO: Python difflib is not exactly the same as unidiff; should
 
 
536
          either fix it up or prefer to use an external diff.
 
 
538
    TODO: If a directory is given, diff everything under that.
 
 
540
    TODO: Selected-file diff is inefficient and doesn't show you
 
 
543
    TODO: This probably handles non-Unix newlines poorly.
 
 
551
    takes_args = ['file*']
 
 
552
    takes_options = ['revision', 'diff-options']
 
 
553
    aliases = ['di', 'dif']
 
 
555
    def run(self, revision=None, file_list=None, diff_options=None):
 
 
556
        from bzrlib.diff import show_diff
 
 
559
            b = find_branch(file_list[0])
 
 
560
            file_list = [b.relpath(f) for f in file_list]
 
 
561
            if file_list == ['']:
 
 
562
                # just pointing to top-of-tree
 
 
567
        if revision is not None:
 
 
568
            if len(revision) == 1:
 
 
569
                show_diff(b, revision[0], specific_files=file_list,
 
 
570
                          external_diff_options=diff_options)
 
 
571
            elif len(revision) == 2:
 
 
572
                show_diff(b, revision[0], specific_files=file_list,
 
 
573
                          external_diff_options=diff_options,
 
 
574
                          revision2=revision[1])
 
 
576
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
 
578
            show_diff(b, None, specific_files=file_list,
 
 
579
                      external_diff_options=diff_options)
 
 
584
class cmd_deleted(Command):
 
 
585
    """List files deleted in the working tree.
 
 
587
    TODO: Show files deleted since a previous revision, or between two revisions.
 
 
589
    def run(self, show_ids=False):
 
 
592
        new = b.working_tree()
 
 
594
        ## TODO: Much more efficient way to do this: read in new
 
 
595
        ## directories with readdir, rather than stating each one.  Same
 
 
596
        ## level of effort but possibly much less IO.  (Or possibly not,
 
 
597
        ## if the directories are very large...)
 
 
599
        for path, ie in old.inventory.iter_entries():
 
 
600
            if not new.has_id(ie.file_id):
 
 
602
                    print '%-50s %s' % (path, ie.file_id)
 
 
607
class cmd_modified(Command):
 
 
608
    """List files modified in working tree."""
 
 
611
        from bzrlib.delta import compare_trees
 
 
614
        td = compare_trees(b.basis_tree(), b.working_tree())
 
 
616
        for path, id, kind in td.modified:
 
 
621
class cmd_added(Command):
 
 
622
    """List files added in working tree."""
 
 
626
        wt = b.working_tree()
 
 
627
        basis_inv = b.basis_tree().inventory
 
 
630
            if file_id in basis_inv:
 
 
632
            path = inv.id2path(file_id)
 
 
633
            if not os.access(b.abspath(path), os.F_OK):
 
 
639
class cmd_root(Command):
 
 
640
    """Show the tree root directory.
 
 
642
    The root is the nearest enclosing directory with a .bzr control
 
 
644
    takes_args = ['filename?']
 
 
645
    def run(self, filename=None):
 
 
646
        """Print the branch root."""
 
 
647
        b = find_branch(filename)
 
 
648
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
 
 
651
class cmd_log(Command):
 
 
652
    """Show log of this branch.
 
 
654
    To request a range of logs, you can use the command -r begin:end
 
 
655
    -r revision requests a specific revision, -r :end or -r begin: are
 
 
658
    --message allows you to give a regular expression, which will be evaluated
 
 
659
    so that only matching entries will be displayed.
 
 
661
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
 
665
    takes_args = ['filename?']
 
 
666
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
 
 
667
                     'long', 'message', 'short',]
 
 
669
    def run(self, filename=None, timezone='original',
 
 
677
        from bzrlib.log import log_formatter, show_log
 
 
680
        direction = (forward and 'forward') or 'reverse'
 
 
683
            b = find_branch(filename)
 
 
684
            fp = b.relpath(filename)
 
 
686
                file_id = b.read_working_inventory().path2id(fp)
 
 
688
                file_id = None  # points to branch root
 
 
696
        elif len(revision) == 1:
 
 
697
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
 
 
698
        elif len(revision) == 2:
 
 
699
            rev1 = b.get_revision_info(revision[0])[0]
 
 
700
            rev2 = b.get_revision_info(revision[1])[0]
 
 
702
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
 
709
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
 
711
        # use 'replace' so that we don't abort if trying to write out
 
 
712
        # in e.g. the default C locale.
 
 
713
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
 
719
        lf = log_formatter(log_format,
 
 
722
                           show_timezone=timezone)
 
 
735
class cmd_touching_revisions(Command):
 
 
736
    """Return revision-ids which affected a particular file.
 
 
738
    A more user-friendly interface is "bzr log FILE"."""
 
 
740
    takes_args = ["filename"]
 
 
741
    def run(self, filename):
 
 
742
        b = find_branch(filename)
 
 
743
        inv = b.read_working_inventory()
 
 
744
        file_id = inv.path2id(b.relpath(filename))
 
 
745
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
 
746
            print "%6d %s" % (revno, what)
 
 
749
class cmd_ls(Command):
 
 
750
    """List files in a tree.
 
 
752
    TODO: Take a revision or remote path and list that tree instead.
 
 
755
    def run(self, revision=None, verbose=False):
 
 
758
            tree = b.working_tree()
 
 
760
            tree = b.revision_tree(b.lookup_revision(revision))
 
 
762
        for fp, fc, kind, fid in tree.list_files():
 
 
764
                if kind == 'directory':
 
 
771
                print '%-8s %s%s' % (fc, fp, kindch)
 
 
777
class cmd_unknowns(Command):
 
 
778
    """List unknown files."""
 
 
780
        from bzrlib.osutils import quotefn
 
 
781
        for f in find_branch('.').unknowns():
 
 
786
class cmd_ignore(Command):
 
 
787
    """Ignore a command or pattern.
 
 
789
    To remove patterns from the ignore list, edit the .bzrignore file.
 
 
791
    If the pattern contains a slash, it is compared to the whole path
 
 
792
    from the branch root.  Otherwise, it is comapred to only the last
 
 
793
    component of the path.
 
 
795
    Ignore patterns are case-insensitive on case-insensitive systems.
 
 
797
    Note: wildcards must be quoted from the shell on Unix.
 
 
800
        bzr ignore ./Makefile
 
 
803
    takes_args = ['name_pattern']
 
 
805
    def run(self, name_pattern):
 
 
806
        from bzrlib.atomicfile import AtomicFile
 
 
810
        ifn = b.abspath('.bzrignore')
 
 
812
        if os.path.exists(ifn):
 
 
815
                igns = f.read().decode('utf-8')
 
 
821
        # TODO: If the file already uses crlf-style termination, maybe
 
 
822
        # we should use that for the newly added lines?
 
 
824
        if igns and igns[-1] != '\n':
 
 
826
        igns += name_pattern + '\n'
 
 
829
            f = AtomicFile(ifn, 'wt')
 
 
830
            f.write(igns.encode('utf-8'))
 
 
835
        inv = b.working_tree().inventory
 
 
836
        if inv.path2id('.bzrignore'):
 
 
837
            mutter('.bzrignore is already versioned')
 
 
839
            mutter('need to make new .bzrignore file versioned')
 
 
840
            b.add(['.bzrignore'])
 
 
844
class cmd_ignored(Command):
 
 
845
    """List ignored files and the patterns that matched them.
 
 
847
    See also: bzr ignore"""
 
 
849
        tree = find_branch('.').working_tree()
 
 
850
        for path, file_class, kind, file_id in tree.list_files():
 
 
851
            if file_class != 'I':
 
 
853
            ## XXX: Slightly inefficient since this was already calculated
 
 
854
            pat = tree.is_ignored(path)
 
 
855
            print '%-50s %s' % (path, pat)
 
 
858
class cmd_lookup_revision(Command):
 
 
859
    """Lookup the revision-id from a revision-number
 
 
862
        bzr lookup-revision 33
 
 
865
    takes_args = ['revno']
 
 
867
    def run(self, revno):
 
 
871
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
 
873
        print find_branch('.').lookup_revision(revno)
 
 
876
class cmd_export(Command):
 
 
877
    """Export past revision to destination directory.
 
 
879
    If no revision is specified this exports the last committed revision.
 
 
881
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
 
882
    given, try to find the format with the extension. If no extension
 
 
883
    is found exports to a directory (equivalent to --format=dir).
 
 
885
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
 
886
    is given, the top directory will be the root name of the file."""
 
 
887
    # TODO: list known exporters
 
 
888
    takes_args = ['dest']
 
 
889
    takes_options = ['revision', 'format', 'root']
 
 
890
    def run(self, dest, revision=None, format=None, root=None):
 
 
894
            rev_id = b.last_patch()
 
 
896
            if len(revision) != 1:
 
 
897
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
 
898
            revno, rev_id = b.get_revision_info(revision[0])
 
 
899
        t = b.revision_tree(rev_id)
 
 
900
        root, ext = os.path.splitext(dest)
 
 
904
            elif ext in (".gz", ".tgz"):
 
 
906
            elif ext in (".bz2", ".tbz2"):
 
 
910
        t.export(dest, format, root)
 
 
913
class cmd_cat(Command):
 
 
914
    """Write a file's text from a previous revision."""
 
 
916
    takes_options = ['revision']
 
 
917
    takes_args = ['filename']
 
 
919
    def run(self, filename, revision=None):
 
 
921
            raise BzrCommandError("bzr cat requires a revision number")
 
 
922
        elif len(revision) != 1:
 
 
923
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
 
925
        b.print_file(b.relpath(filename), revision[0])
 
 
928
class cmd_local_time_offset(Command):
 
 
929
    """Show the offset in seconds from GMT to local time."""
 
 
932
        print bzrlib.osutils.local_time_offset()
 
 
936
class cmd_commit(Command):
 
 
937
    """Commit changes into a new revision.
 
 
939
    If no arguments are given, the entire tree is committed.
 
 
941
    If selected files are specified, only changes to those files are
 
 
942
    committed.  If a directory is specified then the directory and everything 
 
 
943
    within it is committed.
 
 
945
    A selected-file commit may fail in some cases where the committed
 
 
946
    tree would be invalid, such as trying to commit a file in a
 
 
947
    newly-added directory that is not itself committed.
 
 
949
    TODO: Run hooks on tree to-be-committed, and after commit.
 
 
951
    TODO: Strict commit that fails if there are unknown or deleted files.
 
 
953
    takes_args = ['selected*']
 
 
954
    takes_options = ['message', 'file', 'verbose', 'unchanged']
 
 
955
    aliases = ['ci', 'checkin']
 
 
957
    # TODO: Give better message for -s, --summary, used by tla people
 
 
959
    # XXX: verbose currently does nothing
 
 
961
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
 
963
        from bzrlib.errors import PointlessCommit
 
 
964
        from bzrlib.msgeditor import edit_commit_message
 
 
965
        from bzrlib.status import show_status
 
 
966
        from cStringIO import StringIO
 
 
970
            selected_list = [b.relpath(s) for s in selected_list]
 
 
972
        if not message and not file:
 
 
974
            show_status(b, specific_files=selected_list,
 
 
976
            message = edit_commit_message(catcher.getvalue())
 
 
979
                raise BzrCommandError("please specify a commit message"
 
 
980
                                      " with either --message or --file")
 
 
981
        elif message and file:
 
 
982
            raise BzrCommandError("please specify either --message or --file")
 
 
986
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
 
990
                     specific_files=selected_list,
 
 
991
                     allow_pointless=unchanged)
 
 
992
        except PointlessCommit:
 
 
993
            # FIXME: This should really happen before the file is read in;
 
 
994
            # perhaps prepare the commit; get the message; then actually commit
 
 
995
            raise BzrCommandError("no changes to commit",
 
 
996
                                  ["use --unchanged to commit anyhow"])
 
 
999
class cmd_check(Command):
 
 
1000
    """Validate consistency of branch history.
 
 
1002
    This command checks various invariants about the branch storage to
 
 
1003
    detect data corruption or bzr bugs.
 
 
1005
    If given the --update flag, it will update some optional fields
 
 
1006
    to help ensure data consistency.
 
 
1008
    takes_args = ['dir?']
 
 
1010
    def run(self, dir='.'):
 
 
1011
        from bzrlib.check import check
 
 
1013
        check(find_branch(dir))
 
 
1016
class cmd_scan_cache(Command):
 
 
1019
        from bzrlib.hashcache import HashCache
 
 
1025
        print '%6d stats' % c.stat_count
 
 
1026
        print '%6d in hashcache' % len(c._cache)
 
 
1027
        print '%6d files removed from cache' % c.removed_count
 
 
1028
        print '%6d hashes updated' % c.update_count
 
 
1029
        print '%6d files changed too recently to cache' % c.danger_count
 
 
1036
class cmd_upgrade(Command):
 
 
1037
    """Upgrade branch storage to current format.
 
 
1039
    The check command or bzr developers may sometimes advise you to run
 
 
1042
    takes_args = ['dir?']
 
 
1044
    def run(self, dir='.'):
 
 
1045
        from bzrlib.upgrade import upgrade
 
 
1046
        upgrade(find_branch(dir))
 
 
1050
class cmd_whoami(Command):
 
 
1051
    """Show bzr user id."""
 
 
1052
    takes_options = ['email']
 
 
1054
    def run(self, email=False):
 
 
1056
            b = bzrlib.branch.find_branch('.')
 
 
1061
            print bzrlib.osutils.user_email(b)
 
 
1063
            print bzrlib.osutils.username(b)
 
 
1066
class cmd_selftest(Command):
 
 
1067
    """Run internal test suite"""
 
 
1069
    takes_options = ['verbose', 'pattern']
 
 
1070
    def run(self, verbose=False, pattern=".*"):
 
 
1072
        from bzrlib.selftest import selftest
 
 
1073
        # we don't want progress meters from the tests to go to the
 
 
1074
        # real output; and we don't want log messages cluttering up
 
 
1076
        save_ui = bzrlib.ui.ui_factory
 
 
1077
        bzrlib.trace.info('running tests...')
 
 
1079
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
 
1080
            result = selftest(verbose=verbose, pattern=pattern)
 
 
1082
                bzrlib.trace.info('tests passed')
 
 
1084
                bzrlib.trace.info('tests failed')
 
 
1085
            return int(not result)
 
 
1087
            bzrlib.ui.ui_factory = save_ui
 
 
1091
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
 
1092
    # is bzrlib itself in a branch?
 
 
1093
    bzrrev = bzrlib.get_bzr_revision()
 
 
1095
        print "  (bzr checkout, revision %d {%s})" % bzrrev
 
 
1096
    print bzrlib.__copyright__
 
 
1097
    print "http://bazaar-ng.org/"
 
 
1099
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
 
1100
    print "you may use, modify and redistribute it under the terms of the GNU"
 
 
1101
    print "General Public License version 2 or later."
 
 
1104
class cmd_version(Command):
 
 
1105
    """Show version of bzr."""
 
 
1109
class cmd_rocks(Command):
 
 
1110
    """Statement of optimism."""
 
 
1113
        print "it sure does!"
 
 
1116
class cmd_find_merge_base(Command):
 
 
1117
    """Find and print a base revision for merging two branches.
 
 
1119
    TODO: Options to specify revisions on either side, as if
 
 
1120
          merging only part of the history.
 
 
1122
    takes_args = ['branch', 'other']
 
 
1125
    def run(self, branch, other):
 
 
1126
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
 
 
1128
        branch1 = find_branch(branch)
 
 
1129
        branch2 = find_branch(other)
 
 
1131
        history_1 = branch1.revision_history()
 
 
1132
        history_2 = branch2.revision_history()
 
 
1134
        last1 = branch1.last_patch()
 
 
1135
        last2 = branch2.last_patch()
 
 
1137
        source = MultipleRevisionSources(branch1, branch2)
 
 
1139
        base_rev_id = common_ancestor(last1, last2, source)
 
 
1141
        print 'merge base is revision %s' % base_rev_id
 
 
1145
        if base_revno is None:
 
 
1146
            raise bzrlib.errors.UnrelatedBranches()
 
 
1148
        print ' r%-6d in %s' % (base_revno, branch)
 
 
1150
        other_revno = branch2.revision_id_to_revno(base_revid)
 
 
1152
        print ' r%-6d in %s' % (other_revno, other)
 
 
1156
class cmd_merge(Command):
 
 
1157
    """Perform a three-way merge.
 
 
1159
    The branch is the branch you will merge from.  By default, it will
 
 
1160
    merge the latest revision.  If you specify a revision, that
 
 
1161
    revision will be merged.  If you specify two revisions, the first
 
 
1162
    will be used as a BASE, and the second one as OTHER.  Revision
 
 
1163
    numbers are always relative to the specified branch.
 
 
1165
    By default bzr will try to merge in all new work from the other
 
 
1166
    branch, automatically determining an appropriate base.  If this
 
 
1167
    fails, you may need to give an explicit base.
 
 
1171
    To merge the latest revision from bzr.dev
 
 
1172
    bzr merge ../bzr.dev
 
 
1174
    To merge changes up to and including revision 82 from bzr.dev
 
 
1175
    bzr merge -r 82 ../bzr.dev
 
 
1177
    To merge the changes introduced by 82, without previous changes:
 
 
1178
    bzr merge -r 81..82 ../bzr.dev
 
 
1180
    merge refuses to run if there are any uncommitted changes, unless
 
 
1183
    takes_args = ['branch?']
 
 
1184
    takes_options = ['revision', 'force', 'merge-type']
 
 
1186
    def run(self, branch='.', revision=None, force=False, 
 
 
1188
        from bzrlib.merge import merge
 
 
1189
        from bzrlib.merge_core import ApplyMerge3
 
 
1190
        if merge_type is None:
 
 
1191
            merge_type = ApplyMerge3
 
 
1193
        if revision is None or len(revision) < 1:
 
 
1195
            other = [branch, -1]
 
 
1197
            if len(revision) == 1:
 
 
1198
                other = [branch, revision[0]]
 
 
1201
                assert len(revision) == 2
 
 
1202
                if None in revision:
 
 
1203
                    raise BzrCommandError(
 
 
1204
                        "Merge doesn't permit that revision specifier.")
 
 
1205
                base = [branch, revision[0]]
 
 
1206
                other = [branch, revision[1]]
 
 
1209
            merge(other, base, check_clean=(not force), merge_type=merge_type)
 
 
1210
        except bzrlib.errors.AmbiguousBase, e:
 
 
1211
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
 
1212
                 "candidates are:\n  "
 
 
1213
                 + "\n  ".join(e.bases)
 
 
1215
                 "please specify an explicit base with -r,\n"
 
 
1216
                 "and (if you want) report this to the bzr developers\n")
 
 
1220
class cmd_revert(Command):
 
 
1221
    """Reverse all changes since the last commit.
 
 
1223
    Only versioned files are affected.  Specify filenames to revert only 
 
 
1224
    those files.  By default, any files that are changed will be backed up
 
 
1225
    first.  Backup files have a '~' appended to their name.
 
 
1227
    takes_options = ['revision', 'no-backup']
 
 
1228
    takes_args = ['file*']
 
 
1229
    aliases = ['merge-revert']
 
 
1231
    def run(self, revision=None, no_backup=False, file_list=None):
 
 
1232
        from bzrlib.merge import merge
 
 
1233
        from bzrlib.branch import Branch
 
 
1234
        from bzrlib.commands import parse_spec
 
 
1236
        if file_list is not None:
 
 
1237
            if len(file_list) == 0:
 
 
1238
                raise BzrCommandError("No files specified")
 
 
1239
        if revision is None:
 
 
1241
        elif len(revision) != 1:
 
 
1242
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
 
1243
        merge(('.', revision[0]), parse_spec('.'),
 
 
1246
              backup_files=not no_backup,
 
 
1247
              file_list=file_list)
 
 
1249
            Branch('.').set_pending_merges([])
 
 
1252
class cmd_assert_fail(Command):
 
 
1253
    """Test reporting of assertion failures"""
 
 
1256
        assert False, "always fails"
 
 
1259
class cmd_help(Command):
 
 
1260
    """Show help on a command or other topic.
 
 
1262
    For a list of all available commands, say 'bzr help commands'."""
 
 
1263
    takes_options = ['long']
 
 
1264
    takes_args = ['topic?']
 
 
1267
    def run(self, topic=None, long=False):
 
 
1269
        if topic is None and long:
 
 
1274
class cmd_shell_complete(Command):
 
 
1275
    """Show appropriate completions for context.
 
 
1277
    For a list of all available commands, say 'bzr shell-complete'."""
 
 
1278
    takes_args = ['context?']
 
 
1282
    def run(self, context=None):
 
 
1283
        import shellcomplete
 
 
1284
        shellcomplete.shellcomplete(context)
 
 
1287
class cmd_fetch(Command):
 
 
1288
    """Copy in history from another branch but don't merge it.
 
 
1290
    This is an internal method used for pull and merge."""
 
 
1292
    takes_args = ['from_branch', 'to_branch']
 
 
1293
    def run(self, from_branch, to_branch):
 
 
1294
        from bzrlib.fetch import Fetcher
 
 
1295
        from bzrlib.branch import Branch
 
 
1296
        from_b = Branch(from_branch)
 
 
1297
        to_b = Branch(to_branch)
 
 
1298
        Fetcher(to_b, from_b)
 
 
1302
class cmd_missing(Command):
 
 
1303
    """What is missing in this branch relative to other branch.
 
 
1305
    # TODO: rewrite this in terms of ancestry so that it shows only
 
 
1308
    takes_args = ['remote?']
 
 
1309
    aliases = ['mis', 'miss']
 
 
1310
    # We don't have to add quiet to the list, because 
 
 
1311
    # unknown options are parsed as booleans
 
 
1312
    takes_options = ['verbose', 'quiet']
 
 
1314
    def run(self, remote=None, verbose=False, quiet=False):
 
 
1315
        from bzrlib.errors import BzrCommandError
 
 
1316
        from bzrlib.missing import show_missing
 
 
1318
        if verbose and quiet:
 
 
1319
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
 
1321
        b = find_branch('.')
 
 
1322
        parent = b.get_parent()
 
 
1325
                raise BzrCommandError("No missing location known or specified.")
 
 
1328
                    print "Using last location: %s" % parent
 
 
1330
        elif parent is None:
 
 
1331
            # We only update x-pull if it did not exist, missing should not change the parent
 
 
1332
            b.controlfile('x-pull', 'wb').write(remote + '\n')
 
 
1333
        br_remote = find_branch(remote)
 
 
1335
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
 
1339
class cmd_plugins(Command):
 
 
1343
        import bzrlib.plugin
 
 
1344
        from inspect import getdoc
 
 
1345
        for plugin in bzrlib.plugin.all_plugins:
 
 
1346
            if hasattr(plugin, '__path__'):
 
 
1347
                print plugin.__path__[0]
 
 
1348
            elif hasattr(plugin, '__file__'):
 
 
1349
                print plugin.__file__
 
 
1355
                print '\t', d.split('\n')[0]