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 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
    # XXX: FIXME: bzr status should accept a -r option to show changes
 
 
67
    # relative to a revision, or between revisions
 
 
69
    takes_args = ['file*']
 
 
70
    takes_options = ['all', 'show-ids']
 
 
71
    aliases = ['st', 'stat']
 
 
73
    def run(self, all=False, show_ids=False, file_list=None):
 
 
75
            b = Branch.open_containing(file_list[0])
 
 
76
            file_list = [b.relpath(x) for x in file_list]
 
 
77
            # special case: only one path was given and it's the root
 
 
82
            b = Branch.open_containing('.')
 
 
84
        from bzrlib.status import show_status
 
 
85
        show_status(b, show_unchanged=all, show_ids=show_ids,
 
 
86
                    specific_files=file_list)
 
 
89
class cmd_cat_revision(Command):
 
 
90
    """Write out metadata for a revision."""
 
 
93
    takes_args = ['revision_id']
 
 
95
    def run(self, revision_id):
 
 
96
        b = Branch.open_containing('.')
 
 
97
        sys.stdout.write(b.get_revision_xml_file(revision_id).read())
 
 
100
class cmd_revno(Command):
 
 
101
    """Show current revision number.
 
 
103
    This is equal to the number of revisions on this branch."""
 
 
105
        print Branch.open_containing('.').revno()
 
 
108
class cmd_revision_info(Command):
 
 
109
    """Show revision number and revision id for a given revision identifier.
 
 
112
    takes_args = ['revision_info*']
 
 
113
    takes_options = ['revision']
 
 
114
    def run(self, revision=None, revision_info_list=()):
 
 
115
        from bzrlib.revisionspec import RevisionSpec
 
 
118
        if revision is not None:
 
 
119
            revs.extend(revision)
 
 
120
        for rev in revision_info_list:
 
 
121
            revs.append(RevisionSpec(revision_info_list))
 
 
123
            raise BzrCommandError('You must supply a revision identifier')
 
 
125
        b = Branch.open_containing('.')
 
 
128
            print '%4d %s' % rev.in_history(b)
 
 
131
class cmd_add(Command):
 
 
132
    """Add specified files or directories.
 
 
134
    In non-recursive mode, all the named items are added, regardless
 
 
135
    of whether they were previously ignored.  A warning is given if
 
 
136
    any of the named files are already versioned.
 
 
138
    In recursive mode (the default), files are treated the same way
 
 
139
    but the behaviour for directories is different.  Directories that
 
 
140
    are already versioned do not give a warning.  All directories,
 
 
141
    whether already versioned or not, are searched for files or
 
 
142
    subdirectories that are neither versioned or ignored, and these
 
 
143
    are added.  This search proceeds recursively into versioned
 
 
144
    directories.  If no names are given '.' is assumed.
 
 
146
    Therefore simply saying 'bzr add' will version all files that
 
 
147
    are currently unknown.
 
 
149
    Adding a file whose parent directory is not versioned will
 
 
150
    implicitly add the parent, and so on up to the root. This means
 
 
151
    you should never need to explictly add a directory, they'll just
 
 
152
    get added when you add a file in the directory.
 
 
154
    takes_args = ['file*']
 
 
155
    takes_options = ['verbose', 'no-recurse']
 
 
157
    def run(self, file_list, verbose=False, no_recurse=False):
 
 
158
        # verbose currently has no effect
 
 
159
        from bzrlib.add import smart_add, add_reporter_print
 
 
160
        smart_add(file_list, not no_recurse, add_reporter_print)
 
 
164
class cmd_mkdir(Command):
 
 
165
    """Create a new versioned directory.
 
 
167
    This is equivalent to creating the directory and then adding it.
 
 
169
    takes_args = ['dir+']
 
 
171
    def run(self, dir_list):
 
 
177
                b = Branch.open_containing(d)
 
 
182
class cmd_relpath(Command):
 
 
183
    """Show path of a file relative to root"""
 
 
184
    takes_args = ['filename']
 
 
187
    def run(self, filename):
 
 
188
        print Branch.open_containing(filename).relpath(filename)
 
 
192
class cmd_inventory(Command):
 
 
193
    """Show inventory of the current working copy or a revision."""
 
 
194
    takes_options = ['revision', 'show-ids']
 
 
196
    def run(self, revision=None, show_ids=False):
 
 
197
        b = Branch.open_containing('.')
 
 
199
            inv = b.read_working_inventory()
 
 
201
            if len(revision) > 1:
 
 
202
                raise BzrCommandError('bzr inventory --revision takes'
 
 
203
                    ' exactly one revision identifier')
 
 
204
            inv = b.get_revision_inventory(revision[0].in_history(b).rev_id)
 
 
206
        for path, entry in inv.entries():
 
 
208
                print '%-50s %s' % (path, entry.file_id)
 
 
213
class cmd_move(Command):
 
 
214
    """Move files to a different directory.
 
 
219
    The destination must be a versioned directory in the same branch.
 
 
221
    takes_args = ['source$', 'dest']
 
 
222
    def run(self, source_list, dest):
 
 
223
        b = Branch.open_containing('.')
 
 
225
        # TODO: glob expansion on windows?
 
 
226
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
 
 
229
class cmd_rename(Command):
 
 
230
    """Change the name of an entry.
 
 
233
      bzr rename frob.c frobber.c
 
 
234
      bzr rename src/frob.c lib/frob.c
 
 
236
    It is an error if the destination name exists.
 
 
238
    See also the 'move' command, which moves files into a different
 
 
239
    directory without changing their name.
 
 
241
    TODO: Some way to rename multiple files without invoking bzr for each
 
 
243
    takes_args = ['from_name', 'to_name']
 
 
245
    def run(self, from_name, to_name):
 
 
246
        b = Branch.open_containing('.')
 
 
247
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
 
 
251
class cmd_mv(Command):
 
 
252
    """Move or rename a file.
 
 
255
        bzr mv OLDNAME NEWNAME
 
 
256
        bzr mv SOURCE... DESTINATION
 
 
258
    If the last argument is a versioned directory, all the other names
 
 
259
    are moved into it.  Otherwise, there must be exactly two arguments
 
 
260
    and the file is changed to a new name, which must not already exist.
 
 
262
    Files cannot be moved between branches.
 
 
264
    takes_args = ['names*']
 
 
265
    def run(self, names_list):
 
 
266
        if len(names_list) < 2:
 
 
267
            raise BzrCommandError("missing file argument")
 
 
268
        b = Branch.open_containing(names_list[0])
 
 
270
        rel_names = [b.relpath(x) for x in names_list]
 
 
272
        if os.path.isdir(names_list[-1]):
 
 
273
            # move into existing directory
 
 
274
            for pair in b.move(rel_names[:-1], rel_names[-1]):
 
 
275
                print "%s => %s" % pair
 
 
277
            if len(names_list) != 2:
 
 
278
                raise BzrCommandError('to mv multiple files the destination '
 
 
279
                                      'must be a versioned directory')
 
 
280
            b.rename_one(rel_names[0], rel_names[1])
 
 
281
            print "%s => %s" % (rel_names[0], rel_names[1])
 
 
286
class cmd_pull(Command):
 
 
287
    """Pull any changes from another branch into the current one.
 
 
289
    If the location is omitted, the last-used location will be used.
 
 
290
    Both the revision history and the working directory will be
 
 
293
    This command only works on branches that have not diverged.  Branches are
 
 
294
    considered diverged if both branches have had commits without first
 
 
295
    pulling from the other.
 
 
297
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
 
298
    from one into the other.
 
 
300
    takes_args = ['location?']
 
 
302
    def run(self, location=None):
 
 
303
        from bzrlib.merge import merge
 
 
305
        from shutil import rmtree
 
 
308
        br_to = Branch.open_containing('.')
 
 
309
        stored_loc = br_to.get_parent()
 
 
311
            if stored_loc is None:
 
 
312
                raise BzrCommandError("No pull location known or specified.")
 
 
314
                print "Using last location: %s" % stored_loc
 
 
315
                location = stored_loc
 
 
316
        cache_root = tempfile.mkdtemp()
 
 
317
        from bzrlib.errors import DivergedBranches
 
 
318
        br_from = Branch.open_containing(location)
 
 
319
        location = br_from.base
 
 
320
        old_revno = br_to.revno()
 
 
322
            from bzrlib.errors import DivergedBranches
 
 
323
            br_from = Branch.open(location)
 
 
324
            br_from.setup_caching(cache_root)
 
 
325
            location = br_from.base
 
 
326
            old_revno = br_to.revno()
 
 
328
                br_to.update_revisions(br_from)
 
 
329
            except DivergedBranches:
 
 
330
                raise BzrCommandError("These branches have diverged."
 
 
333
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
 
334
            if location != stored_loc:
 
 
335
                br_to.set_parent(location)
 
 
341
class cmd_branch(Command):
 
 
342
    """Create a new copy of a branch.
 
 
344
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
 
345
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
 
347
    To retrieve the branch as of a particular revision, supply the --revision
 
 
348
    parameter, as in "branch foo/bar -r 5".
 
 
350
    takes_args = ['from_location', 'to_location?']
 
 
351
    takes_options = ['revision']
 
 
352
    aliases = ['get', 'clone']
 
 
354
    def run(self, from_location, to_location=None, revision=None):
 
 
355
        from bzrlib.branch import copy_branch
 
 
358
        from shutil import rmtree
 
 
359
        cache_root = tempfile.mkdtemp()
 
 
363
            elif len(revision) > 1:
 
 
364
                raise BzrCommandError(
 
 
365
                    'bzr branch --revision takes exactly 1 revision value')
 
 
367
                br_from = Branch.open(from_location)
 
 
369
                if e.errno == errno.ENOENT:
 
 
370
                    raise BzrCommandError('Source location "%s" does not'
 
 
371
                                          ' exist.' % to_location)
 
 
374
            br_from.setup_caching(cache_root)
 
 
375
            if to_location is None:
 
 
376
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
 
378
                os.mkdir(to_location)
 
 
380
                if e.errno == errno.EEXIST:
 
 
381
                    raise BzrCommandError('Target directory "%s" already'
 
 
382
                                          ' exists.' % to_location)
 
 
383
                if e.errno == errno.ENOENT:
 
 
384
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
 
389
                copy_branch(br_from, to_location, revision[0])
 
 
390
            except bzrlib.errors.NoSuchRevision:
 
 
392
                msg = "The branch %s has no revision %d." % (from_location, revision[0])
 
 
393
                raise BzrCommandError(msg)
 
 
398
class cmd_renames(Command):
 
 
399
    """Show list of renamed files.
 
 
401
    TODO: Option to show renames between two historical versions.
 
 
403
    TODO: Only show renames under dir, rather than in the whole branch.
 
 
405
    takes_args = ['dir?']
 
 
407
    def run(self, dir='.'):
 
 
408
        b = Branch.open_containing(dir)
 
 
409
        old_inv = b.basis_tree().inventory
 
 
410
        new_inv = b.read_working_inventory()
 
 
412
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
 
414
        for old_name, new_name in renames:
 
 
415
            print "%s => %s" % (old_name, new_name)        
 
 
418
class cmd_info(Command):
 
 
419
    """Show statistical information about a branch."""
 
 
420
    takes_args = ['branch?']
 
 
422
    def run(self, branch=None):
 
 
425
        b = Branch.open_containing(branch)
 
 
429
class cmd_remove(Command):
 
 
430
    """Make a file unversioned.
 
 
432
    This makes bzr stop tracking changes to a versioned file.  It does
 
 
433
    not delete the working copy.
 
 
435
    takes_args = ['file+']
 
 
436
    takes_options = ['verbose']
 
 
438
    def run(self, file_list, verbose=False):
 
 
439
        b = Branch.open_containing(file_list[0])
 
 
440
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
 
 
443
class cmd_file_id(Command):
 
 
444
    """Print file_id of a particular file or directory.
 
 
446
    The file_id is assigned when the file is first added and remains the
 
 
447
    same through all revisions where the file exists, even when it is
 
 
451
    takes_args = ['filename']
 
 
452
    def run(self, filename):
 
 
453
        b = Branch.open_containing(filename)
 
 
454
        i = b.inventory.path2id(b.relpath(filename))
 
 
456
            raise BzrError("%r is not a versioned file" % filename)
 
 
461
class cmd_file_path(Command):
 
 
462
    """Print path of file_ids to a file or directory.
 
 
464
    This prints one line for each directory down to the target,
 
 
465
    starting at the branch root."""
 
 
467
    takes_args = ['filename']
 
 
468
    def run(self, filename):
 
 
469
        b = Branch.open_containing(filename)
 
 
471
        fid = inv.path2id(b.relpath(filename))
 
 
473
            raise BzrError("%r is not a versioned file" % filename)
 
 
474
        for fip in inv.get_idpath(fid):
 
 
478
class cmd_revision_history(Command):
 
 
479
    """Display list of revision ids on this branch."""
 
 
482
        for patchid in Branch.open_containing('.').revision_history():
 
 
486
class cmd_directories(Command):
 
 
487
    """Display list of versioned directories in this branch."""
 
 
489
        for name, ie in Branch.open_containing('.').read_working_inventory().directories():
 
 
496
class cmd_init(Command):
 
 
497
    """Make a directory into a versioned branch.
 
 
499
    Use this to create an empty branch, or before importing an
 
 
502
    Recipe for importing a tree of files:
 
 
507
        bzr commit -m 'imported project'
 
 
510
        from bzrlib.branch import Branch
 
 
511
        Branch.initialize('.')
 
 
514
class cmd_diff(Command):
 
 
515
    """Show differences in working tree.
 
 
517
    If files are listed, only the changes in those files are listed.
 
 
518
    Otherwise, all changes for the tree are listed.
 
 
520
    TODO: Allow diff across branches.
 
 
522
    TODO: Option to use external diff command; could be GNU diff, wdiff,
 
 
525
    TODO: Python difflib is not exactly the same as unidiff; should
 
 
526
          either fix it up or prefer to use an external diff.
 
 
528
    TODO: If a directory is given, diff everything under that.
 
 
530
    TODO: Selected-file diff is inefficient and doesn't show you
 
 
533
    TODO: This probably handles non-Unix newlines poorly.
 
 
541
    takes_args = ['file*']
 
 
542
    takes_options = ['revision', 'diff-options']
 
 
543
    aliases = ['di', 'dif']
 
 
545
    def run(self, revision=None, file_list=None, diff_options=None):
 
 
546
        from bzrlib.diff import show_diff
 
 
549
            b = Branch.open_containing(file_list[0])
 
 
550
            file_list = [b.relpath(f) for f in file_list]
 
 
551
            if file_list == ['']:
 
 
552
                # just pointing to top-of-tree
 
 
555
            b = Branch.open_containing('.')
 
 
557
        if revision is not None:
 
 
558
            if len(revision) == 1:
 
 
559
                show_diff(b, revision[0], specific_files=file_list,
 
 
560
                          external_diff_options=diff_options)
 
 
561
            elif len(revision) == 2:
 
 
562
                show_diff(b, revision[0], specific_files=file_list,
 
 
563
                          external_diff_options=diff_options,
 
 
564
                          revision2=revision[1])
 
 
566
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
 
568
            show_diff(b, None, specific_files=file_list,
 
 
569
                      external_diff_options=diff_options)
 
 
574
class cmd_deleted(Command):
 
 
575
    """List files deleted in the working tree.
 
 
577
    TODO: Show files deleted since a previous revision, or between two revisions.
 
 
579
    def run(self, show_ids=False):
 
 
580
        b = Branch.open_containing('.')
 
 
582
        new = b.working_tree()
 
 
584
        ## TODO: Much more efficient way to do this: read in new
 
 
585
        ## directories with readdir, rather than stating each one.  Same
 
 
586
        ## level of effort but possibly much less IO.  (Or possibly not,
 
 
587
        ## if the directories are very large...)
 
 
589
        for path, ie in old.inventory.iter_entries():
 
 
590
            if not new.has_id(ie.file_id):
 
 
592
                    print '%-50s %s' % (path, ie.file_id)
 
 
597
class cmd_modified(Command):
 
 
598
    """List files modified in working tree."""
 
 
601
        from bzrlib.delta import compare_trees
 
 
603
        b = Branch.open_containing('.')
 
 
604
        td = compare_trees(b.basis_tree(), b.working_tree())
 
 
606
        for path, id, kind in td.modified:
 
 
611
class cmd_added(Command):
 
 
612
    """List files added in working tree."""
 
 
615
        b = Branch.open_containing('.')
 
 
616
        wt = b.working_tree()
 
 
617
        basis_inv = b.basis_tree().inventory
 
 
620
            if file_id in basis_inv:
 
 
622
            path = inv.id2path(file_id)
 
 
623
            if not os.access(b.abspath(path), os.F_OK):
 
 
629
class cmd_root(Command):
 
 
630
    """Show the tree root directory.
 
 
632
    The root is the nearest enclosing directory with a .bzr control
 
 
634
    takes_args = ['filename?']
 
 
635
    def run(self, filename=None):
 
 
636
        """Print the branch root."""
 
 
637
        b = Branch.open_containing(filename)
 
 
641
class cmd_log(Command):
 
 
642
    """Show log of this branch.
 
 
644
    To request a range of logs, you can use the command -r begin:end
 
 
645
    -r revision requests a specific revision, -r :end or -r begin: are
 
 
648
    --message allows you to give a regular expression, which will be evaluated
 
 
649
    so that only matching entries will be displayed.
 
 
651
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
 
655
    takes_args = ['filename?']
 
 
656
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
 
 
657
                     'long', 'message', 'short',]
 
 
659
    def run(self, filename=None, timezone='original',
 
 
667
        from bzrlib.log import log_formatter, show_log
 
 
670
        direction = (forward and 'forward') or 'reverse'
 
 
673
            b = Branch.open_containing(filename)
 
 
674
            fp = b.relpath(filename)
 
 
676
                file_id = b.read_working_inventory().path2id(fp)
 
 
678
                file_id = None  # points to branch root
 
 
680
            b = Branch.open_containing('.')
 
 
686
        elif len(revision) == 1:
 
 
687
            rev1 = rev2 = revision[0].in_history(b).revno
 
 
688
        elif len(revision) == 2:
 
 
689
            rev1 = revision[0].in_history(b).revno
 
 
690
            rev2 = revision[1].in_history(b).revno
 
 
692
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
 
699
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
 
701
        # use 'replace' so that we don't abort if trying to write out
 
 
702
        # in e.g. the default C locale.
 
 
703
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
 
709
        lf = log_formatter(log_format,
 
 
712
                           show_timezone=timezone)
 
 
725
class cmd_touching_revisions(Command):
 
 
726
    """Return revision-ids which affected a particular file.
 
 
728
    A more user-friendly interface is "bzr log FILE"."""
 
 
730
    takes_args = ["filename"]
 
 
731
    def run(self, filename):
 
 
732
        b = Branch.open_containing(filename)
 
 
733
        inv = b.read_working_inventory()
 
 
734
        file_id = inv.path2id(b.relpath(filename))
 
 
735
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
 
736
            print "%6d %s" % (revno, what)
 
 
739
class cmd_ls(Command):
 
 
740
    """List files in a tree.
 
 
742
    TODO: Take a revision or remote path and list that tree instead.
 
 
745
    def run(self, revision=None, verbose=False):
 
 
746
        b = Branch.open_containing('.')
 
 
748
            tree = b.working_tree()
 
 
750
            tree = b.revision_tree(revision.in_history(b).rev_id)
 
 
752
        for fp, fc, kind, fid in tree.list_files():
 
 
754
                if kind == 'directory':
 
 
761
                print '%-8s %s%s' % (fc, fp, kindch)
 
 
767
class cmd_unknowns(Command):
 
 
768
    """List unknown files."""
 
 
770
        from bzrlib.osutils import quotefn
 
 
771
        for f in Branch.open_containing('.').unknowns():
 
 
776
class cmd_ignore(Command):
 
 
777
    """Ignore a command or pattern.
 
 
779
    To remove patterns from the ignore list, edit the .bzrignore file.
 
 
781
    If the pattern contains a slash, it is compared to the whole path
 
 
782
    from the branch root.  Otherwise, it is comapred to only the last
 
 
783
    component of the path.
 
 
785
    Ignore patterns are case-insensitive on case-insensitive systems.
 
 
787
    Note: wildcards must be quoted from the shell on Unix.
 
 
790
        bzr ignore ./Makefile
 
 
793
    takes_args = ['name_pattern']
 
 
795
    def run(self, name_pattern):
 
 
796
        from bzrlib.atomicfile import AtomicFile
 
 
799
        b = Branch.open_containing('.')
 
 
800
        ifn = b.abspath('.bzrignore')
 
 
802
        if os.path.exists(ifn):
 
 
805
                igns = f.read().decode('utf-8')
 
 
811
        # TODO: If the file already uses crlf-style termination, maybe
 
 
812
        # we should use that for the newly added lines?
 
 
814
        if igns and igns[-1] != '\n':
 
 
816
        igns += name_pattern + '\n'
 
 
819
            f = AtomicFile(ifn, 'wt')
 
 
820
            f.write(igns.encode('utf-8'))
 
 
825
        inv = b.working_tree().inventory
 
 
826
        if inv.path2id('.bzrignore'):
 
 
827
            mutter('.bzrignore is already versioned')
 
 
829
            mutter('need to make new .bzrignore file versioned')
 
 
830
            b.add(['.bzrignore'])
 
 
834
class cmd_ignored(Command):
 
 
835
    """List ignored files and the patterns that matched them.
 
 
837
    See also: bzr ignore"""
 
 
839
        tree = Branch.open_containing('.').working_tree()
 
 
840
        for path, file_class, kind, file_id in tree.list_files():
 
 
841
            if file_class != 'I':
 
 
843
            ## XXX: Slightly inefficient since this was already calculated
 
 
844
            pat = tree.is_ignored(path)
 
 
845
            print '%-50s %s' % (path, pat)
 
 
848
class cmd_lookup_revision(Command):
 
 
849
    """Lookup the revision-id from a revision-number
 
 
852
        bzr lookup-revision 33
 
 
855
    takes_args = ['revno']
 
 
857
    def run(self, revno):
 
 
861
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
 
863
        print Branch.open_containing('.').get_rev_id(revno)
 
 
866
class cmd_export(Command):
 
 
867
    """Export past revision to destination directory.
 
 
869
    If no revision is specified this exports the last committed revision.
 
 
871
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
 
872
    given, try to find the format with the extension. If no extension
 
 
873
    is found exports to a directory (equivalent to --format=dir).
 
 
875
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
 
876
    is given, the top directory will be the root name of the file."""
 
 
877
    # TODO: list known exporters
 
 
878
    takes_args = ['dest']
 
 
879
    takes_options = ['revision', 'format', 'root']
 
 
880
    def run(self, dest, revision=None, format=None, root=None):
 
 
882
        b = Branch.open_containing('.')
 
 
884
            rev_id = b.last_patch()
 
 
886
            if len(revision) != 1:
 
 
887
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
 
888
            rev_id = revision[0].in_history(b).rev_id
 
 
889
        t = b.revision_tree(rev_id)
 
 
890
        root, ext = os.path.splitext(dest)
 
 
894
            elif ext in (".gz", ".tgz"):
 
 
896
            elif ext in (".bz2", ".tbz2"):
 
 
900
        t.export(dest, format, root)
 
 
903
class cmd_cat(Command):
 
 
904
    """Write a file's text from a previous revision."""
 
 
906
    takes_options = ['revision']
 
 
907
    takes_args = ['filename']
 
 
909
    def run(self, filename, revision=None):
 
 
911
            raise BzrCommandError("bzr cat requires a revision number")
 
 
912
        elif len(revision) != 1:
 
 
913
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
 
914
        b = Branch.open_containing('.')
 
 
915
        b.print_file(b.relpath(filename), revision[0].in_history(b).revno)
 
 
918
class cmd_local_time_offset(Command):
 
 
919
    """Show the offset in seconds from GMT to local time."""
 
 
922
        print bzrlib.osutils.local_time_offset()
 
 
926
class cmd_commit(Command):
 
 
927
    """Commit changes into a new revision.
 
 
929
    If no arguments are given, the entire tree is committed.
 
 
931
    If selected files are specified, only changes to those files are
 
 
932
    committed.  If a directory is specified then the directory and everything 
 
 
933
    within it is committed.
 
 
935
    A selected-file commit may fail in some cases where the committed
 
 
936
    tree would be invalid, such as trying to commit a file in a
 
 
937
    newly-added directory that is not itself committed.
 
 
939
    TODO: Run hooks on tree to-be-committed, and after commit.
 
 
941
    TODO: Strict commit that fails if there are unknown or deleted files.
 
 
943
    takes_args = ['selected*']
 
 
944
    takes_options = ['message', 'file', 'verbose', 'unchanged']
 
 
945
    aliases = ['ci', 'checkin']
 
 
947
    # TODO: Give better message for -s, --summary, used by tla people
 
 
949
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
 
951
        from bzrlib.errors import PointlessCommit
 
 
952
        from bzrlib.msgeditor import edit_commit_message
 
 
953
        from bzrlib.status import show_status
 
 
954
        from cStringIO import StringIO
 
 
956
        b = Branch.open_containing('.')
 
 
958
            selected_list = [b.relpath(s) for s in selected_list]
 
 
960
        if not message and not file:
 
 
962
            show_status(b, specific_files=selected_list,
 
 
964
            message = edit_commit_message(catcher.getvalue())
 
 
967
                raise BzrCommandError("please specify a commit message"
 
 
968
                                      " with either --message or --file")
 
 
969
        elif message and file:
 
 
970
            raise BzrCommandError("please specify either --message or --file")
 
 
974
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
 
977
            b.commit(message, verbose=verbose,
 
 
978
                     specific_files=selected_list,
 
 
979
                     allow_pointless=unchanged)
 
 
980
        except PointlessCommit:
 
 
981
            # FIXME: This should really happen before the file is read in;
 
 
982
            # perhaps prepare the commit; get the message; then actually commit
 
 
983
            raise BzrCommandError("no changes to commit",
 
 
984
                                  ["use --unchanged to commit anyhow"])
 
 
987
class cmd_check(Command):
 
 
988
    """Validate consistency of branch history.
 
 
990
    This command checks various invariants about the branch storage to
 
 
991
    detect data corruption or bzr bugs.
 
 
993
    takes_args = ['dir?']
 
 
995
    def run(self, dir='.'):
 
 
996
        from bzrlib.check import check
 
 
998
        check(Branch.open_containing(dir))
 
 
1001
class cmd_scan_cache(Command):
 
 
1004
        from bzrlib.hashcache import HashCache
 
 
1010
        print '%6d stats' % c.stat_count
 
 
1011
        print '%6d in hashcache' % len(c._cache)
 
 
1012
        print '%6d files removed from cache' % c.removed_count
 
 
1013
        print '%6d hashes updated' % c.update_count
 
 
1014
        print '%6d files changed too recently to cache' % c.danger_count
 
 
1021
class cmd_upgrade(Command):
 
 
1022
    """Upgrade branch storage to current format.
 
 
1024
    The check command or bzr developers may sometimes advise you to run
 
 
1027
    takes_args = ['dir?']
 
 
1029
    def run(self, dir='.'):
 
 
1030
        from bzrlib.upgrade import upgrade
 
 
1031
        upgrade(Branch.open_containing(dir))
 
 
1035
class cmd_whoami(Command):
 
 
1036
    """Show bzr user id."""
 
 
1037
    takes_options = ['email']
 
 
1039
    def run(self, email=False):
 
 
1041
            b = bzrlib.branch.Branch.open_containing('.')
 
 
1046
            print bzrlib.osutils.user_email(b)
 
 
1048
            print bzrlib.osutils.username(b)
 
 
1051
class cmd_selftest(Command):
 
 
1052
    """Run internal test suite"""
 
 
1054
    takes_options = ['verbose', 'pattern']
 
 
1055
    def run(self, verbose=False, pattern=".*"):
 
 
1057
        from bzrlib.selftest import selftest
 
 
1058
        # we don't want progress meters from the tests to go to the
 
 
1059
        # real output; and we don't want log messages cluttering up
 
 
1061
        save_ui = bzrlib.ui.ui_factory
 
 
1062
        bzrlib.trace.info('running tests...')
 
 
1064
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
 
1065
            result = selftest(verbose=verbose, pattern=pattern)
 
 
1067
                bzrlib.trace.info('tests passed')
 
 
1069
                bzrlib.trace.info('tests failed')
 
 
1070
            return int(not result)
 
 
1072
            bzrlib.ui.ui_factory = save_ui
 
 
1076
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
 
1077
    # is bzrlib itself in a branch?
 
 
1078
    bzrrev = bzrlib.get_bzr_revision()
 
 
1080
        print "  (bzr checkout, revision %d {%s})" % bzrrev
 
 
1081
    print bzrlib.__copyright__
 
 
1082
    print "http://bazaar-ng.org/"
 
 
1084
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
 
1085
    print "you may use, modify and redistribute it under the terms of the GNU"
 
 
1086
    print "General Public License version 2 or later."
 
 
1089
class cmd_version(Command):
 
 
1090
    """Show version of bzr."""
 
 
1094
class cmd_rocks(Command):
 
 
1095
    """Statement of optimism."""
 
 
1098
        print "it sure does!"
 
 
1101
class cmd_find_merge_base(Command):
 
 
1102
    """Find and print a base revision for merging two branches.
 
 
1104
    TODO: Options to specify revisions on either side, as if
 
 
1105
          merging only part of the history.
 
 
1107
    takes_args = ['branch', 'other']
 
 
1110
    def run(self, branch, other):
 
 
1111
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
 
 
1113
        branch1 = Branch.open_containing(branch)
 
 
1114
        branch2 = Branch.open_containing(other)
 
 
1116
        history_1 = branch1.revision_history()
 
 
1117
        history_2 = branch2.revision_history()
 
 
1119
        last1 = branch1.last_patch()
 
 
1120
        last2 = branch2.last_patch()
 
 
1122
        source = MultipleRevisionSources(branch1, branch2)
 
 
1124
        base_rev_id = common_ancestor(last1, last2, source)
 
 
1126
        print 'merge base is revision %s' % base_rev_id
 
 
1130
        if base_revno is None:
 
 
1131
            raise bzrlib.errors.UnrelatedBranches()
 
 
1133
        print ' r%-6d in %s' % (base_revno, branch)
 
 
1135
        other_revno = branch2.revision_id_to_revno(base_revid)
 
 
1137
        print ' r%-6d in %s' % (other_revno, other)
 
 
1141
class cmd_merge(Command):
 
 
1142
    """Perform a three-way merge.
 
 
1144
    The branch is the branch you will merge from.  By default, it will
 
 
1145
    merge the latest revision.  If you specify a revision, that
 
 
1146
    revision will be merged.  If you specify two revisions, the first
 
 
1147
    will be used as a BASE, and the second one as OTHER.  Revision
 
 
1148
    numbers are always relative to the specified branch.
 
 
1150
    By default bzr will try to merge in all new work from the other
 
 
1151
    branch, automatically determining an appropriate base.  If this
 
 
1152
    fails, you may need to give an explicit base.
 
 
1156
    To merge the latest revision from bzr.dev
 
 
1157
    bzr merge ../bzr.dev
 
 
1159
    To merge changes up to and including revision 82 from bzr.dev
 
 
1160
    bzr merge -r 82 ../bzr.dev
 
 
1162
    To merge the changes introduced by 82, without previous changes:
 
 
1163
    bzr merge -r 81..82 ../bzr.dev
 
 
1165
    merge refuses to run if there are any uncommitted changes, unless
 
 
1168
    takes_args = ['branch?']
 
 
1169
    takes_options = ['revision', 'force', 'merge-type']
 
 
1171
    def run(self, branch='.', revision=None, force=False, 
 
 
1173
        from bzrlib.merge import merge
 
 
1174
        from bzrlib.merge_core import ApplyMerge3
 
 
1175
        if merge_type is None:
 
 
1176
            merge_type = ApplyMerge3
 
 
1178
        if revision is None or len(revision) < 1:
 
 
1180
            other = [branch, -1]
 
 
1182
            if len(revision) == 1:
 
 
1184
                other = [branch, revision[0].in_history(branch).revno]
 
 
1186
                assert len(revision) == 2
 
 
1187
                if None in revision:
 
 
1188
                    raise BzrCommandError(
 
 
1189
                        "Merge doesn't permit that revision specifier.")
 
 
1190
                base = [branch, revision[0].in_history(branch).revno]
 
 
1191
                other = [branch, revision[1].in_history(branch).revno]
 
 
1194
            merge(other, base, check_clean=(not force), merge_type=merge_type)
 
 
1195
        except bzrlib.errors.AmbiguousBase, e:
 
 
1196
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
 
1197
                 "candidates are:\n  "
 
 
1198
                 + "\n  ".join(e.bases)
 
 
1200
                 "please specify an explicit base with -r,\n"
 
 
1201
                 "and (if you want) report this to the bzr developers\n")
 
 
1205
class cmd_revert(Command):
 
 
1206
    """Reverse all changes since the last commit.
 
 
1208
    Only versioned files are affected.  Specify filenames to revert only 
 
 
1209
    those files.  By default, any files that are changed will be backed up
 
 
1210
    first.  Backup files have a '~' appended to their name.
 
 
1212
    takes_options = ['revision', 'no-backup']
 
 
1213
    takes_args = ['file*']
 
 
1214
    aliases = ['merge-revert']
 
 
1216
    def run(self, revision=None, no_backup=False, file_list=None):
 
 
1217
        from bzrlib.merge import merge
 
 
1218
        from bzrlib.branch import Branch
 
 
1219
        from bzrlib.commands import parse_spec
 
 
1221
        if file_list is not None:
 
 
1222
            if len(file_list) == 0:
 
 
1223
                raise BzrCommandError("No files specified")
 
 
1224
        if revision is None:
 
 
1226
        elif len(revision) != 1:
 
 
1227
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
 
1228
        merge(('.', revision[0]), parse_spec('.'),
 
 
1231
              backup_files=not no_backup,
 
 
1232
              file_list=file_list)
 
 
1234
            Branch.open_containing('.').set_pending_merges([])
 
 
1237
class cmd_assert_fail(Command):
 
 
1238
    """Test reporting of assertion failures"""
 
 
1241
        assert False, "always fails"
 
 
1244
class cmd_help(Command):
 
 
1245
    """Show help on a command or other topic.
 
 
1247
    For a list of all available commands, say 'bzr help commands'."""
 
 
1248
    takes_options = ['long']
 
 
1249
    takes_args = ['topic?']
 
 
1252
    def run(self, topic=None, long=False):
 
 
1254
        if topic is None and long:
 
 
1259
class cmd_shell_complete(Command):
 
 
1260
    """Show appropriate completions for context.
 
 
1262
    For a list of all available commands, say 'bzr shell-complete'."""
 
 
1263
    takes_args = ['context?']
 
 
1267
    def run(self, context=None):
 
 
1268
        import shellcomplete
 
 
1269
        shellcomplete.shellcomplete(context)
 
 
1272
class cmd_missing(Command):
 
 
1273
    """What is missing in this branch relative to other branch.
 
 
1275
    takes_args = ['remote?']
 
 
1276
    aliases = ['mis', 'miss']
 
 
1277
    # We don't have to add quiet to the list, because 
 
 
1278
    # unknown options are parsed as booleans
 
 
1279
    takes_options = ['verbose', 'quiet']
 
 
1281
    def run(self, remote=None, verbose=False, quiet=False):
 
 
1282
        from bzrlib.errors import BzrCommandError
 
 
1283
        from bzrlib.missing import show_missing
 
 
1285
        if verbose and quiet:
 
 
1286
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
 
1288
        b = Branch.open_containing('.')
 
 
1289
        parent = b.get_parent()
 
 
1292
                raise BzrCommandError("No missing location known or specified.")
 
 
1295
                    print "Using last location: %s" % parent
 
 
1297
        elif parent is None:
 
 
1298
            # We only update parent if it did not exist, missing
 
 
1299
            # should not change the parent
 
 
1300
            b.set_parent(remote)
 
 
1301
        br_remote = Branch.open_containing(remote)
 
 
1302
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
 
1305
class cmd_plugins(Command):
 
 
1309
        import bzrlib.plugin
 
 
1310
        from inspect import getdoc
 
 
1311
        for plugin in bzrlib.plugin.all_plugins:
 
 
1312
            if hasattr(plugin, '__path__'):
 
 
1313
                print plugin.__path__[0]
 
 
1314
            elif hasattr(plugin, '__file__'):
 
 
1315
                print plugin.__file__
 
 
1321
                print '\t', d.split('\n')[0]