~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Danny van Heumen
  • Date: 2010-03-09 21:42:11 UTC
  • mto: (4634.139.5 2.0)
  • mto: This revision was merged to the branch mainline in revision 5160.
  • Revision ID: danny@dannyvanheumen.nl-20100309214211-iqh42x6qcikgd9p3
Reverted now-useless TODO list.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
 
23
import codecs
23
24
import cStringIO
24
25
import sys
25
26
import time
30
31
    bundle,
31
32
    btree_index,
32
33
    bzrdir,
33
 
    directory_service,
34
34
    delta,
35
 
    config as _mod_config,
 
35
    config,
36
36
    errors,
37
37
    globbing,
38
38
    hooks,
43
43
    reconfigure,
44
44
    rename_map,
45
45
    revision as _mod_revision,
46
 
    static_tuple,
47
46
    symbol_versioning,
48
 
    timestamp,
49
47
    transport,
50
48
    ui,
51
49
    urlutils,
53
51
    )
54
52
from bzrlib.branch import Branch
55
53
from bzrlib.conflicts import ConflictList
56
 
from bzrlib.transport import memory
57
54
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
58
55
from bzrlib.smtp_connection import SMTPConnection
59
56
from bzrlib.workingtree import WorkingTree
60
57
""")
61
58
 
62
 
from bzrlib.commands import (
63
 
    Command,
64
 
    builtin_command_registry,
65
 
    display_command,
66
 
    )
 
59
from bzrlib.commands import Command, display_command
67
60
from bzrlib.option import (
68
61
    ListOption,
69
62
    Option,
74
67
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
75
68
 
76
69
 
77
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
78
70
def tree_files(file_list, default_branch=u'.', canonicalize=True,
79
71
    apply_view=True):
80
 
    return internal_tree_files(file_list, default_branch, canonicalize,
81
 
        apply_view)
 
72
    try:
 
73
        return internal_tree_files(file_list, default_branch, canonicalize,
 
74
            apply_view)
 
75
    except errors.FileInWrongBranch, e:
 
76
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
 
77
                                     (e.path, file_list[0]))
82
78
 
83
79
 
84
80
def tree_files_for_add(file_list):
148
144
 
149
145
# XXX: Bad function name; should possibly also be a class method of
150
146
# WorkingTree rather than a function.
151
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
152
147
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
153
148
    apply_view=True):
154
149
    """Convert command-line paths to a WorkingTree and relative paths.
155
150
 
156
 
    Deprecated: use WorkingTree.open_containing_paths instead.
157
 
 
158
151
    This is typically used for command-line processors that take one or
159
152
    more filenames, and infer the workingtree that contains them.
160
153
 
170
163
 
171
164
    :return: workingtree, [relative_paths]
172
165
    """
173
 
    return WorkingTree.open_containing_paths(
174
 
        file_list, default_directory='.',
175
 
        canonicalize=True,
176
 
        apply_view=True)
 
166
    if file_list is None or len(file_list) == 0:
 
167
        tree = WorkingTree.open_containing(default_branch)[0]
 
168
        if tree.supports_views() and apply_view:
 
169
            view_files = tree.views.lookup_view()
 
170
            if view_files:
 
171
                file_list = view_files
 
172
                view_str = views.view_display_str(view_files)
 
173
                note("Ignoring files outside view. View is %s" % view_str)
 
174
        return tree, file_list
 
175
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
176
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
177
        apply_view=apply_view)
 
178
 
 
179
 
 
180
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
 
181
    """Convert file_list into a list of relpaths in tree.
 
182
 
 
183
    :param tree: A tree to operate on.
 
184
    :param file_list: A list of user provided paths or None.
 
185
    :param apply_view: if True and a view is set, apply it or check that
 
186
        specified files are within it
 
187
    :return: A list of relative paths.
 
188
    :raises errors.PathNotChild: When a provided path is in a different tree
 
189
        than tree.
 
190
    """
 
191
    if file_list is None:
 
192
        return None
 
193
    if tree.supports_views() and apply_view:
 
194
        view_files = tree.views.lookup_view()
 
195
    else:
 
196
        view_files = []
 
197
    new_list = []
 
198
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
 
199
    # doesn't - fix that up here before we enter the loop.
 
200
    if canonicalize:
 
201
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
 
202
    else:
 
203
        fixer = tree.relpath
 
204
    for filename in file_list:
 
205
        try:
 
206
            relpath = fixer(osutils.dereference_path(filename))
 
207
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
208
                raise errors.FileOutsideView(filename, view_files)
 
209
            new_list.append(relpath)
 
210
        except errors.PathNotChild:
 
211
            raise errors.FileInWrongBranch(tree.branch, filename)
 
212
    return new_list
177
213
 
178
214
 
179
215
def _get_view_info_for_change_reporter(tree):
188
224
    return view_info
189
225
 
190
226
 
191
 
def _open_directory_or_containing_tree_or_branch(filename, directory):
192
 
    """Open the tree or branch containing the specified file, unless
193
 
    the --directory option is used to specify a different branch."""
194
 
    if directory is not None:
195
 
        return (None, Branch.open(directory), filename)
196
 
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
197
 
 
198
 
 
199
227
# TODO: Make sure no commands unconditionally use the working directory as a
200
228
# branch.  If a filename argument is used, the first of them should be used to
201
229
# specify the branch.  (Perhaps this can be factored out into some kind of
203
231
# opens the branch?)
204
232
 
205
233
class cmd_status(Command):
206
 
    __doc__ = """Display status summary.
 
234
    """Display status summary.
207
235
 
208
236
    This reports on versioned and unknown files, reporting them
209
237
    grouped by state.  Possible states are:
229
257
    unknown
230
258
        Not versioned and not matching an ignore pattern.
231
259
 
232
 
    Additionally for directories, symlinks and files with an executable
233
 
    bit, Bazaar indicates their type using a trailing character: '/', '@'
234
 
    or '*' respectively.
235
 
 
236
260
    To see ignored files use 'bzr ignored'.  For details on the
237
261
    changes to file texts, use 'bzr diff'.
238
262
 
279
303
            raise errors.BzrCommandError('bzr status --revision takes exactly'
280
304
                                         ' one or two revision specifiers')
281
305
 
282
 
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
306
        tree, relfile_list = tree_files(file_list)
283
307
        # Avoid asking for specific files when that is not needed.
284
308
        if relfile_list == ['']:
285
309
            relfile_list = None
296
320
 
297
321
 
298
322
class cmd_cat_revision(Command):
299
 
    __doc__ = """Write out metadata for a revision.
 
323
    """Write out metadata for a revision.
300
324
 
301
325
    The revision to print can either be specified by a specific
302
326
    revision identifier, or you can use --revision.
304
328
 
305
329
    hidden = True
306
330
    takes_args = ['revision_id?']
307
 
    takes_options = ['directory', 'revision']
 
331
    takes_options = ['revision']
308
332
    # cat-revision is more for frontends so should be exact
309
333
    encoding = 'strict'
310
334
 
311
 
    def print_revision(self, revisions, revid):
312
 
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
313
 
        record = stream.next()
314
 
        if record.storage_kind == 'absent':
315
 
            raise errors.NoSuchRevision(revisions, revid)
316
 
        revtext = record.get_bytes_as('fulltext')
317
 
        self.outf.write(revtext.decode('utf-8'))
318
 
 
319
335
    @display_command
320
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
336
    def run(self, revision_id=None, revision=None):
321
337
        if revision_id is not None and revision is not None:
322
338
            raise errors.BzrCommandError('You can only supply one of'
323
339
                                         ' revision_id or --revision')
324
340
        if revision_id is None and revision is None:
325
341
            raise errors.BzrCommandError('You must supply either'
326
342
                                         ' --revision or a revision_id')
327
 
        b = WorkingTree.open_containing(directory)[0].branch
328
 
 
329
 
        revisions = b.repository.revisions
330
 
        if revisions is None:
331
 
            raise errors.BzrCommandError('Repository %r does not support '
332
 
                'access to raw revision texts')
333
 
 
334
 
        b.repository.lock_read()
335
 
        try:
336
 
            # TODO: jam 20060112 should cat-revision always output utf-8?
337
 
            if revision_id is not None:
338
 
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
339
 
                try:
340
 
                    self.print_revision(revisions, revision_id)
341
 
                except errors.NoSuchRevision:
342
 
                    msg = "The repository %s contains no revision %s." % (
343
 
                        b.repository.base, revision_id)
344
 
                    raise errors.BzrCommandError(msg)
345
 
            elif revision is not None:
346
 
                for rev in revision:
347
 
                    if rev is None:
348
 
                        raise errors.BzrCommandError(
349
 
                            'You cannot specify a NULL revision.')
350
 
                    rev_id = rev.as_revision_id(b)
351
 
                    self.print_revision(revisions, rev_id)
352
 
        finally:
353
 
            b.repository.unlock()
354
 
        
 
343
        b = WorkingTree.open_containing(u'.')[0].branch
 
344
 
 
345
        # TODO: jam 20060112 should cat-revision always output utf-8?
 
346
        if revision_id is not None:
 
347
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
 
348
            try:
 
349
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
350
            except errors.NoSuchRevision:
 
351
                msg = "The repository %s contains no revision %s." % (b.repository.base,
 
352
                    revision_id)
 
353
                raise errors.BzrCommandError(msg)
 
354
        elif revision is not None:
 
355
            for rev in revision:
 
356
                if rev is None:
 
357
                    raise errors.BzrCommandError('You cannot specify a NULL'
 
358
                                                 ' revision.')
 
359
                rev_id = rev.as_revision_id(b)
 
360
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
 
361
 
355
362
 
356
363
class cmd_dump_btree(Command):
357
 
    __doc__ = """Dump the contents of a btree index file to stdout.
 
364
    """Dump the contents of a btree index file to stdout.
358
365
 
359
366
    PATH is a btree index file, it can be any URL. This includes things like
360
367
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
424
431
        for node in bt.iter_all_entries():
425
432
            # Node is made up of:
426
433
            # (index, key, value, [references])
427
 
            try:
428
 
                refs = node[3]
429
 
            except IndexError:
430
 
                refs_as_tuples = None
431
 
            else:
432
 
                refs_as_tuples = static_tuple.as_tuples(refs)
433
 
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
434
 
            self.outf.write('%s\n' % (as_tuple,))
 
434
            self.outf.write('%s\n' % (node[1:],))
435
435
 
436
436
 
437
437
class cmd_remove_tree(Command):
438
 
    __doc__ = """Remove the working tree from a given branch/checkout.
 
438
    """Remove the working tree from a given branch/checkout.
439
439
 
440
440
    Since a lightweight checkout is little more than a working tree
441
441
    this will refuse to run against one.
443
443
    To re-create the working tree, use "bzr checkout".
444
444
    """
445
445
    _see_also = ['checkout', 'working-trees']
446
 
    takes_args = ['location*']
 
446
    takes_args = ['location?']
447
447
    takes_options = [
448
448
        Option('force',
449
449
               help='Remove the working tree even if it has '
450
 
                    'uncommitted or shelved changes.'),
 
450
                    'uncommitted changes.'),
451
451
        ]
452
452
 
453
 
    def run(self, location_list, force=False):
454
 
        if not location_list:
455
 
            location_list=['.']
456
 
 
457
 
        for location in location_list:
458
 
            d = bzrdir.BzrDir.open(location)
459
 
            
460
 
            try:
461
 
                working = d.open_workingtree()
462
 
            except errors.NoWorkingTree:
463
 
                raise errors.BzrCommandError("No working tree to remove")
464
 
            except errors.NotLocalUrl:
465
 
                raise errors.BzrCommandError("You cannot remove the working tree"
466
 
                                             " of a remote path")
467
 
            if not force:
468
 
                if (working.has_changes()):
469
 
                    raise errors.UncommittedChanges(working)
470
 
                if working.get_shelf_manager().last_shelf() is not None:
471
 
                    raise errors.ShelvedChanges(working)
472
 
 
473
 
            if working.user_url != working.branch.user_url:
474
 
                raise errors.BzrCommandError("You cannot remove the working tree"
475
 
                                             " from a lightweight checkout")
476
 
 
477
 
            d.destroy_workingtree()
 
453
    def run(self, location='.', force=False):
 
454
        d = bzrdir.BzrDir.open(location)
 
455
 
 
456
        try:
 
457
            working = d.open_workingtree()
 
458
        except errors.NoWorkingTree:
 
459
            raise errors.BzrCommandError("No working tree to remove")
 
460
        except errors.NotLocalUrl:
 
461
            raise errors.BzrCommandError("You cannot remove the working tree"
 
462
                                         " of a remote path")
 
463
        if not force:
 
464
            # XXX: What about pending merges ? -- vila 20090629
 
465
            if working.has_changes(working.basis_tree()):
 
466
                raise errors.UncommittedChanges(working)
 
467
 
 
468
        working_path = working.bzrdir.root_transport.base
 
469
        branch_path = working.branch.bzrdir.root_transport.base
 
470
        if working_path != branch_path:
 
471
            raise errors.BzrCommandError("You cannot remove the working tree"
 
472
                                         " from a lightweight checkout")
 
473
 
 
474
        d.destroy_workingtree()
478
475
 
479
476
 
480
477
class cmd_revno(Command):
481
 
    __doc__ = """Show current revision number.
 
478
    """Show current revision number.
482
479
 
483
480
    This is equal to the number of revisions on this branch.
484
481
    """
494
491
        if tree:
495
492
            try:
496
493
                wt = WorkingTree.open_containing(location)[0]
497
 
                self.add_cleanup(wt.lock_read().unlock)
 
494
                wt.lock_read()
498
495
            except (errors.NoWorkingTree, errors.NotLocalUrl):
499
496
                raise errors.NoWorkingTree(location)
500
 
            revid = wt.last_revision()
501
497
            try:
502
 
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
503
 
            except errors.NoSuchRevision:
504
 
                revno_t = ('???',)
505
 
            revno = ".".join(str(n) for n in revno_t)
 
498
                revid = wt.last_revision()
 
499
                try:
 
500
                    revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
501
                except errors.NoSuchRevision:
 
502
                    revno_t = ('???',)
 
503
                revno = ".".join(str(n) for n in revno_t)
 
504
            finally:
 
505
                wt.unlock()
506
506
        else:
507
507
            b = Branch.open_containing(location)[0]
508
 
            self.add_cleanup(b.lock_read().unlock)
509
 
            revno = b.revno()
510
 
        self.cleanup_now()
 
508
            b.lock_read()
 
509
            try:
 
510
                revno = b.revno()
 
511
            finally:
 
512
                b.unlock()
 
513
 
511
514
        self.outf.write(str(revno) + '\n')
512
515
 
513
516
 
514
517
class cmd_revision_info(Command):
515
 
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
518
    """Show revision number and revision id for a given revision identifier.
516
519
    """
517
520
    hidden = True
518
521
    takes_args = ['revision_info*']
519
522
    takes_options = [
520
523
        'revision',
521
 
        custom_help('directory',
 
524
        Option('directory',
522
525
            help='Branch to examine, '
523
 
                 'rather than the one containing the working directory.'),
 
526
                 'rather than the one containing the working directory.',
 
527
            short_name='d',
 
528
            type=unicode,
 
529
            ),
524
530
        Option('tree', help='Show revno of working tree'),
525
531
        ]
526
532
 
531
537
        try:
532
538
            wt = WorkingTree.open_containing(directory)[0]
533
539
            b = wt.branch
534
 
            self.add_cleanup(wt.lock_read().unlock)
 
540
            wt.lock_read()
535
541
        except (errors.NoWorkingTree, errors.NotLocalUrl):
536
542
            wt = None
537
543
            b = Branch.open_containing(directory)[0]
538
 
            self.add_cleanup(b.lock_read().unlock)
539
 
        revision_ids = []
540
 
        if revision is not None:
541
 
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
542
 
        if revision_info_list is not None:
543
 
            for rev_str in revision_info_list:
544
 
                rev_spec = RevisionSpec.from_string(rev_str)
545
 
                revision_ids.append(rev_spec.as_revision_id(b))
546
 
        # No arguments supplied, default to the last revision
547
 
        if len(revision_ids) == 0:
548
 
            if tree:
549
 
                if wt is None:
550
 
                    raise errors.NoWorkingTree(directory)
551
 
                revision_ids.append(wt.last_revision())
 
544
            b.lock_read()
 
545
        try:
 
546
            revision_ids = []
 
547
            if revision is not None:
 
548
                revision_ids.extend(rev.as_revision_id(b) for rev in revision)
 
549
            if revision_info_list is not None:
 
550
                for rev_str in revision_info_list:
 
551
                    rev_spec = RevisionSpec.from_string(rev_str)
 
552
                    revision_ids.append(rev_spec.as_revision_id(b))
 
553
            # No arguments supplied, default to the last revision
 
554
            if len(revision_ids) == 0:
 
555
                if tree:
 
556
                    if wt is None:
 
557
                        raise errors.NoWorkingTree(directory)
 
558
                    revision_ids.append(wt.last_revision())
 
559
                else:
 
560
                    revision_ids.append(b.last_revision())
 
561
 
 
562
            revinfos = []
 
563
            maxlen = 0
 
564
            for revision_id in revision_ids:
 
565
                try:
 
566
                    dotted_revno = b.revision_id_to_dotted_revno(revision_id)
 
567
                    revno = '.'.join(str(i) for i in dotted_revno)
 
568
                except errors.NoSuchRevision:
 
569
                    revno = '???'
 
570
                maxlen = max(maxlen, len(revno))
 
571
                revinfos.append([revno, revision_id])
 
572
        finally:
 
573
            if wt is None:
 
574
                b.unlock()
552
575
            else:
553
 
                revision_ids.append(b.last_revision())
554
 
 
555
 
        revinfos = []
556
 
        maxlen = 0
557
 
        for revision_id in revision_ids:
558
 
            try:
559
 
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
560
 
                revno = '.'.join(str(i) for i in dotted_revno)
561
 
            except errors.NoSuchRevision:
562
 
                revno = '???'
563
 
            maxlen = max(maxlen, len(revno))
564
 
            revinfos.append([revno, revision_id])
565
 
 
566
 
        self.cleanup_now()
 
576
                wt.unlock()
 
577
 
567
578
        for ri in revinfos:
568
579
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
569
580
 
570
581
 
571
582
class cmd_add(Command):
572
 
    __doc__ = """Add specified files or directories.
 
583
    """Add specified files or directories.
573
584
 
574
585
    In non-recursive mode, all the named items are added, regardless
575
586
    of whether they were previously ignored.  A warning is given if
640
651
                should_print=(not is_quiet()))
641
652
 
642
653
        if base_tree:
643
 
            self.add_cleanup(base_tree.lock_read().unlock)
644
 
        tree, file_list = tree_files_for_add(file_list)
645
 
        added, ignored = tree.smart_add(file_list, not
646
 
            no_recurse, action=action, save=not dry_run)
647
 
        self.cleanup_now()
 
654
            base_tree.lock_read()
 
655
        try:
 
656
            file_list = self._maybe_expand_globs(file_list)
 
657
            tree, file_list = tree_files_for_add(file_list)
 
658
            added, ignored = tree.smart_add(file_list, not
 
659
                no_recurse, action=action, save=not dry_run)
 
660
        finally:
 
661
            if base_tree is not None:
 
662
                base_tree.unlock()
648
663
        if len(ignored) > 0:
649
664
            if verbose:
650
665
                for glob in sorted(ignored.keys()):
654
669
 
655
670
 
656
671
class cmd_mkdir(Command):
657
 
    __doc__ = """Create a new versioned directory.
 
672
    """Create a new versioned directory.
658
673
 
659
674
    This is equivalent to creating the directory and then adding it.
660
675
    """
664
679
 
665
680
    def run(self, dir_list):
666
681
        for d in dir_list:
 
682
            os.mkdir(d)
667
683
            wt, dd = WorkingTree.open_containing(d)
668
 
            base = os.path.dirname(dd)
669
 
            id = wt.path2id(base)
670
 
            if id != None:
671
 
                os.mkdir(d)
672
 
                wt.add([dd])
673
 
                self.outf.write('added %s\n' % d)
674
 
            else:
675
 
                raise errors.NotVersionedError(path=base)
 
684
            wt.add([dd])
 
685
            self.outf.write('added %s\n' % d)
676
686
 
677
687
 
678
688
class cmd_relpath(Command):
679
 
    __doc__ = """Show path of a file relative to root"""
 
689
    """Show path of a file relative to root"""
680
690
 
681
691
    takes_args = ['filename']
682
692
    hidden = True
691
701
 
692
702
 
693
703
class cmd_inventory(Command):
694
 
    __doc__ = """Show inventory of the current working copy or a revision.
 
704
    """Show inventory of the current working copy or a revision.
695
705
 
696
706
    It is possible to limit the output to a particular entry
697
707
    type using the --kind option.  For example: --kind file.
717
727
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
718
728
 
719
729
        revision = _get_one_revision('inventory', revision)
720
 
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
721
 
        self.add_cleanup(work_tree.lock_read().unlock)
722
 
        if revision is not None:
723
 
            tree = revision.as_tree(work_tree.branch)
724
 
 
725
 
            extra_trees = [work_tree]
726
 
            self.add_cleanup(tree.lock_read().unlock)
727
 
        else:
728
 
            tree = work_tree
729
 
            extra_trees = []
730
 
 
731
 
        if file_list is not None:
732
 
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
733
 
                                      require_versioned=True)
734
 
            # find_ids_across_trees may include some paths that don't
735
 
            # exist in 'tree'.
736
 
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
737
 
                             for file_id in file_ids if file_id in tree)
738
 
        else:
739
 
            entries = tree.inventory.entries()
740
 
 
741
 
        self.cleanup_now()
 
730
        work_tree, file_list = tree_files(file_list)
 
731
        work_tree.lock_read()
 
732
        try:
 
733
            if revision is not None:
 
734
                tree = revision.as_tree(work_tree.branch)
 
735
 
 
736
                extra_trees = [work_tree]
 
737
                tree.lock_read()
 
738
            else:
 
739
                tree = work_tree
 
740
                extra_trees = []
 
741
 
 
742
            if file_list is not None:
 
743
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
744
                                          require_versioned=True)
 
745
                # find_ids_across_trees may include some paths that don't
 
746
                # exist in 'tree'.
 
747
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
748
                                 for file_id in file_ids if file_id in tree)
 
749
            else:
 
750
                entries = tree.inventory.entries()
 
751
        finally:
 
752
            tree.unlock()
 
753
            if tree is not work_tree:
 
754
                work_tree.unlock()
 
755
 
742
756
        for path, entry in entries:
743
757
            if kind and kind != entry.kind:
744
758
                continue
750
764
 
751
765
 
752
766
class cmd_mv(Command):
753
 
    __doc__ = """Move or rename a file.
 
767
    """Move or rename a file.
754
768
 
755
769
    :Usage:
756
770
        bzr mv OLDNAME NEWNAME
788
802
            names_list = []
789
803
        if len(names_list) < 2:
790
804
            raise errors.BzrCommandError("missing file argument")
791
 
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
792
 
        self.add_cleanup(tree.lock_tree_write().unlock)
793
 
        self._run(tree, names_list, rel_names, after)
 
805
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
806
        tree.lock_tree_write()
 
807
        try:
 
808
            self._run(tree, names_list, rel_names, after)
 
809
        finally:
 
810
            tree.unlock()
794
811
 
795
812
    def run_auto(self, names_list, after, dry_run):
796
813
        if names_list is not None and len(names_list) > 1:
799
816
        if after:
800
817
            raise errors.BzrCommandError('--after cannot be specified with'
801
818
                                         ' --auto.')
802
 
        work_tree, file_list = WorkingTree.open_containing_paths(
803
 
            names_list, default_directory='.')
804
 
        self.add_cleanup(work_tree.lock_tree_write().unlock)
805
 
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
819
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
820
        work_tree.lock_tree_write()
 
821
        try:
 
822
            rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
823
        finally:
 
824
            work_tree.unlock()
806
825
 
807
826
    def _run(self, tree, names_list, rel_names, after):
808
827
        into_existing = osutils.isdir(names_list[-1])
829
848
            # All entries reference existing inventory items, so fix them up
830
849
            # for cicp file-systems.
831
850
            rel_names = tree.get_canonical_inventory_paths(rel_names)
832
 
            for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
833
 
                if not is_quiet():
834
 
                    self.outf.write("%s => %s\n" % (src, dest))
 
851
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
 
852
                self.outf.write("%s => %s\n" % pair)
835
853
        else:
836
854
            if len(names_list) != 2:
837
855
                raise errors.BzrCommandError('to mv multiple files the'
881
899
            dest = osutils.pathjoin(dest_parent, dest_tail)
882
900
            mutter("attempting to move %s => %s", src, dest)
883
901
            tree.rename_one(src, dest, after=after)
884
 
            if not is_quiet():
885
 
                self.outf.write("%s => %s\n" % (src, dest))
 
902
            self.outf.write("%s => %s\n" % (src, dest))
886
903
 
887
904
 
888
905
class cmd_pull(Command):
889
 
    __doc__ = """Turn this branch into a mirror of another branch.
 
906
    """Turn this branch into a mirror of another branch.
890
907
 
891
 
    By default, this command only works on branches that have not diverged.
892
 
    Branches are considered diverged if the destination branch's most recent 
893
 
    commit is one that has not been merged (directly or indirectly) into the 
894
 
    parent.
 
908
    This command only works on branches that have not diverged.  Branches are
 
909
    considered diverged if the destination branch's most recent commit is one
 
910
    that has not been merged (directly or indirectly) into the parent.
895
911
 
896
912
    If branches have diverged, you can use 'bzr merge' to integrate the changes
897
913
    from one into the other.  Once one branch has merged, the other should
898
914
    be able to pull it again.
899
915
 
900
 
    If you want to replace your local changes and just want your branch to
901
 
    match the remote one, use pull --overwrite. This will work even if the two
902
 
    branches have diverged.
 
916
    If you want to forget your local changes and just update your branch to
 
917
    match the remote one, use pull --overwrite.
903
918
 
904
919
    If there is no default location set, the first pull will set it.  After
905
920
    that, you can omit the location to use the default.  To change the
915
930
    takes_options = ['remember', 'overwrite', 'revision',
916
931
        custom_help('verbose',
917
932
            help='Show logs of pulled revisions.'),
918
 
        custom_help('directory',
 
933
        Option('directory',
919
934
            help='Branch to pull into, '
920
 
                 'rather than the one containing the working directory.'),
 
935
                 'rather than the one containing the working directory.',
 
936
            short_name='d',
 
937
            type=unicode,
 
938
            ),
921
939
        Option('local',
922
940
            help="Perform a local pull in a bound "
923
941
                 "branch.  Local pulls are not applied to "
938
956
        try:
939
957
            tree_to = WorkingTree.open_containing(directory)[0]
940
958
            branch_to = tree_to.branch
941
 
            self.add_cleanup(tree_to.lock_write().unlock)
942
959
        except errors.NoWorkingTree:
943
960
            tree_to = None
944
961
            branch_to = Branch.open_containing(directory)[0]
945
 
            self.add_cleanup(branch_to.lock_write().unlock)
946
 
 
 
962
        
947
963
        if local and not branch_to.get_bound_location():
948
964
            raise errors.LocalRequiresBoundBranch()
949
965
 
979
995
        else:
980
996
            branch_from = Branch.open(location,
981
997
                possible_transports=possible_transports)
982
 
            self.add_cleanup(branch_from.lock_read().unlock)
983
998
 
984
999
            if branch_to.get_parent() is None or remember:
985
1000
                branch_to.set_parent(branch_from.base)
986
1001
 
987
 
        if revision is not None:
988
 
            revision_id = revision.as_revision_id(branch_from)
989
 
 
990
 
        if tree_to is not None:
991
 
            view_info = _get_view_info_for_change_reporter(tree_to)
992
 
            change_reporter = delta._ChangeReporter(
993
 
                unversioned_filter=tree_to.is_ignored,
994
 
                view_info=view_info)
995
 
            result = tree_to.pull(
996
 
                branch_from, overwrite, revision_id, change_reporter,
997
 
                possible_transports=possible_transports, local=local)
998
 
        else:
999
 
            result = branch_to.pull(
1000
 
                branch_from, overwrite, revision_id, local=local)
1001
 
 
1002
 
        result.report(self.outf)
1003
 
        if verbose and result.old_revid != result.new_revid:
1004
 
            log.show_branch_change(
1005
 
                branch_to, self.outf, result.old_revno,
1006
 
                result.old_revid)
 
1002
        if branch_from is not branch_to:
 
1003
            branch_from.lock_read()
 
1004
        try:
 
1005
            if revision is not None:
 
1006
                revision_id = revision.as_revision_id(branch_from)
 
1007
 
 
1008
            branch_to.lock_write()
 
1009
            try:
 
1010
                if tree_to is not None:
 
1011
                    view_info = _get_view_info_for_change_reporter(tree_to)
 
1012
                    change_reporter = delta._ChangeReporter(
 
1013
                        unversioned_filter=tree_to.is_ignored,
 
1014
                        view_info=view_info)
 
1015
                    result = tree_to.pull(
 
1016
                        branch_from, overwrite, revision_id, change_reporter,
 
1017
                        possible_transports=possible_transports, local=local)
 
1018
                else:
 
1019
                    result = branch_to.pull(
 
1020
                        branch_from, overwrite, revision_id, local=local)
 
1021
 
 
1022
                result.report(self.outf)
 
1023
                if verbose and result.old_revid != result.new_revid:
 
1024
                    log.show_branch_change(
 
1025
                        branch_to, self.outf, result.old_revno,
 
1026
                        result.old_revid)
 
1027
            finally:
 
1028
                branch_to.unlock()
 
1029
        finally:
 
1030
            if branch_from is not branch_to:
 
1031
                branch_from.unlock()
1007
1032
 
1008
1033
 
1009
1034
class cmd_push(Command):
1010
 
    __doc__ = """Update a mirror of this branch.
 
1035
    """Update a mirror of this branch.
1011
1036
 
1012
1037
    The target branch will not have its working tree populated because this
1013
1038
    is both expensive, and is not supported on remote file systems.
1037
1062
        Option('create-prefix',
1038
1063
               help='Create the path leading up to the branch '
1039
1064
                    'if it does not already exist.'),
1040
 
        custom_help('directory',
 
1065
        Option('directory',
1041
1066
            help='Branch to push from, '
1042
 
                 'rather than the one containing the working directory.'),
 
1067
                 'rather than the one containing the working directory.',
 
1068
            short_name='d',
 
1069
            type=unicode,
 
1070
            ),
1043
1071
        Option('use-existing-dir',
1044
1072
               help='By default push will fail if the target'
1045
1073
                    ' directory exists, but does not already'
1071
1099
        # Get the source branch
1072
1100
        (tree, br_from,
1073
1101
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1102
        if strict is None:
 
1103
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
 
1104
        if strict is None: strict = True # default value
1074
1105
        # Get the tip's revision_id
1075
1106
        revision = _get_one_revision('push', revision)
1076
1107
        if revision is not None:
1077
1108
            revision_id = revision.in_history(br_from).rev_id
1078
1109
        else:
1079
1110
            revision_id = None
1080
 
        if tree is not None and revision_id is None:
1081
 
            tree.check_changed_or_out_of_date(
1082
 
                strict, 'push_strict',
1083
 
                more_error='Use --no-strict to force the push.',
1084
 
                more_warning='Uncommitted changes will not be pushed.')
 
1111
        if strict and tree is not None and revision_id is None:
 
1112
            if (tree.has_changes(tree.basis_tree())
 
1113
                or len(tree.get_parent_ids()) > 1):
 
1114
                raise errors.UncommittedChanges(
 
1115
                    tree, more='Use --no-strict to force the push.')
 
1116
            if tree.last_revision() != tree.branch.last_revision():
 
1117
                # The tree has lost sync with its branch, there is little
 
1118
                # chance that the user is aware of it but he can still force
 
1119
                # the push with --no-strict
 
1120
                raise errors.OutOfDateTree(
 
1121
                    tree, more='Use --no-strict to force the push.')
 
1122
 
1085
1123
        # Get the stacked_on branch, if any
1086
1124
        if stacked_on is not None:
1087
1125
            stacked_on = urlutils.normalize_url(stacked_on)
1119
1157
 
1120
1158
 
1121
1159
class cmd_branch(Command):
1122
 
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
1160
    """Create a new branch that is a copy of an existing branch.
1123
1161
 
1124
1162
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1125
1163
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1134
1172
 
1135
1173
    _see_also = ['checkout']
1136
1174
    takes_args = ['from_location', 'to_location?']
1137
 
    takes_options = ['revision',
1138
 
        Option('hardlink', help='Hard-link working tree files where possible.'),
1139
 
        Option('files-from', type=str,
1140
 
               help="Get file contents from this tree."),
 
1175
    takes_options = ['revision', Option('hardlink',
 
1176
        help='Hard-link working tree files where possible.'),
1141
1177
        Option('no-tree',
1142
1178
            help="Create a branch without a working-tree."),
1143
1179
        Option('switch',
1154
1190
                    ' directory exists, but does not already'
1155
1191
                    ' have a control directory.  This flag will'
1156
1192
                    ' allow branch to proceed.'),
1157
 
        Option('bind',
1158
 
            help="Bind new branch to from location."),
1159
1193
        ]
1160
1194
    aliases = ['get', 'clone']
1161
1195
 
1162
1196
    def run(self, from_location, to_location=None, revision=None,
1163
1197
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1164
 
            use_existing_dir=False, switch=False, bind=False,
1165
 
            files_from=None):
 
1198
            use_existing_dir=False, switch=False):
1166
1199
        from bzrlib import switch as _mod_switch
1167
1200
        from bzrlib.tag import _merge_tags_if_possible
1168
1201
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1169
1202
            from_location)
1170
 
        if not (hardlink or files_from):
1171
 
            # accelerator_tree is usually slower because you have to read N
1172
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1173
 
            # explicitly request it
 
1203
        if (accelerator_tree is not None and
 
1204
            accelerator_tree.supports_content_filtering()):
1174
1205
            accelerator_tree = None
1175
 
        if files_from is not None and files_from != from_location:
1176
 
            accelerator_tree = WorkingTree.open(files_from)
1177
1206
        revision = _get_one_revision('branch', revision)
1178
 
        self.add_cleanup(br_from.lock_read().unlock)
1179
 
        if revision is not None:
1180
 
            revision_id = revision.as_revision_id(br_from)
1181
 
        else:
1182
 
            # FIXME - wt.last_revision, fallback to branch, fall back to
1183
 
            # None or perhaps NULL_REVISION to mean copy nothing
1184
 
            # RBC 20060209
1185
 
            revision_id = br_from.last_revision()
1186
 
        if to_location is None:
1187
 
            to_location = urlutils.derive_to_location(from_location)
1188
 
        to_transport = transport.get_transport(to_location)
 
1207
        br_from.lock_read()
1189
1208
        try:
1190
 
            to_transport.mkdir('.')
1191
 
        except errors.FileExists:
1192
 
            if not use_existing_dir:
1193
 
                raise errors.BzrCommandError('Target directory "%s" '
1194
 
                    'already exists.' % to_location)
 
1209
            if revision is not None:
 
1210
                revision_id = revision.as_revision_id(br_from)
1195
1211
            else:
1196
 
                try:
1197
 
                    bzrdir.BzrDir.open_from_transport(to_transport)
1198
 
                except errors.NotBranchError:
1199
 
                    pass
 
1212
                # FIXME - wt.last_revision, fallback to branch, fall back to
 
1213
                # None or perhaps NULL_REVISION to mean copy nothing
 
1214
                # RBC 20060209
 
1215
                revision_id = br_from.last_revision()
 
1216
            if to_location is None:
 
1217
                to_location = urlutils.derive_to_location(from_location)
 
1218
            to_transport = transport.get_transport(to_location)
 
1219
            try:
 
1220
                to_transport.mkdir('.')
 
1221
            except errors.FileExists:
 
1222
                if not use_existing_dir:
 
1223
                    raise errors.BzrCommandError('Target directory "%s" '
 
1224
                        'already exists.' % to_location)
1200
1225
                else:
1201
 
                    raise errors.AlreadyBranchError(to_location)
1202
 
        except errors.NoSuchFile:
1203
 
            raise errors.BzrCommandError('Parent of "%s" does not exist.'
1204
 
                                         % to_location)
1205
 
        try:
1206
 
            # preserve whatever source format we have.
1207
 
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1208
 
                                        possible_transports=[to_transport],
1209
 
                                        accelerator_tree=accelerator_tree,
1210
 
                                        hardlink=hardlink, stacked=stacked,
1211
 
                                        force_new_repo=standalone,
1212
 
                                        create_tree_if_local=not no_tree,
1213
 
                                        source_branch=br_from)
1214
 
            branch = dir.open_branch()
1215
 
        except errors.NoSuchRevision:
1216
 
            to_transport.delete_tree('.')
1217
 
            msg = "The branch %s has no revision %s." % (from_location,
1218
 
                revision)
1219
 
            raise errors.BzrCommandError(msg)
1220
 
        _merge_tags_if_possible(br_from, branch)
1221
 
        # If the source branch is stacked, the new branch may
1222
 
        # be stacked whether we asked for that explicitly or not.
1223
 
        # We therefore need a try/except here and not just 'if stacked:'
1224
 
        try:
1225
 
            note('Created new stacked branch referring to %s.' %
1226
 
                branch.get_stacked_on_url())
1227
 
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1228
 
            errors.UnstackableRepositoryFormat), e:
1229
 
            note('Branched %d revision(s).' % branch.revno())
1230
 
        if bind:
1231
 
            # Bind to the parent
1232
 
            parent_branch = Branch.open(from_location)
1233
 
            branch.bind(parent_branch)
1234
 
            note('New branch bound to %s' % from_location)
1235
 
        if switch:
1236
 
            # Switch to the new branch
1237
 
            wt, _ = WorkingTree.open_containing('.')
1238
 
            _mod_switch.switch(wt.bzrdir, branch)
1239
 
            note('Switched to branch: %s',
1240
 
                urlutils.unescape_for_display(branch.base, 'utf-8'))
 
1226
                    try:
 
1227
                        bzrdir.BzrDir.open_from_transport(to_transport)
 
1228
                    except errors.NotBranchError:
 
1229
                        pass
 
1230
                    else:
 
1231
                        raise errors.AlreadyBranchError(to_location)
 
1232
            except errors.NoSuchFile:
 
1233
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
 
1234
                                             % to_location)
 
1235
            try:
 
1236
                # preserve whatever source format we have.
 
1237
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
1238
                                            possible_transports=[to_transport],
 
1239
                                            accelerator_tree=accelerator_tree,
 
1240
                                            hardlink=hardlink, stacked=stacked,
 
1241
                                            force_new_repo=standalone,
 
1242
                                            create_tree_if_local=not no_tree,
 
1243
                                            source_branch=br_from)
 
1244
                branch = dir.open_branch()
 
1245
            except errors.NoSuchRevision:
 
1246
                to_transport.delete_tree('.')
 
1247
                msg = "The branch %s has no revision %s." % (from_location,
 
1248
                    revision)
 
1249
                raise errors.BzrCommandError(msg)
 
1250
            _merge_tags_if_possible(br_from, branch)
 
1251
            # If the source branch is stacked, the new branch may
 
1252
            # be stacked whether we asked for that explicitly or not.
 
1253
            # We therefore need a try/except here and not just 'if stacked:'
 
1254
            try:
 
1255
                note('Created new stacked branch referring to %s.' %
 
1256
                    branch.get_stacked_on_url())
 
1257
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
1258
                errors.UnstackableRepositoryFormat), e:
 
1259
                note('Branched %d revision(s).' % branch.revno())
 
1260
            if switch:
 
1261
                # Switch to the new branch
 
1262
                wt, _ = WorkingTree.open_containing('.')
 
1263
                _mod_switch.switch(wt.bzrdir, branch)
 
1264
                note('Switched to branch: %s',
 
1265
                    urlutils.unescape_for_display(branch.base, 'utf-8'))
 
1266
        finally:
 
1267
            br_from.unlock()
1241
1268
 
1242
1269
 
1243
1270
class cmd_checkout(Command):
1244
 
    __doc__ = """Create a new checkout of an existing branch.
 
1271
    """Create a new checkout of an existing branch.
1245
1272
 
1246
1273
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1247
1274
    the branch found in '.'. This is useful if you have removed the working tree
1286
1313
            to_location = branch_location
1287
1314
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1288
1315
            branch_location)
1289
 
        if not (hardlink or files_from):
1290
 
            # accelerator_tree is usually slower because you have to read N
1291
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1292
 
            # explicitly request it
1293
 
            accelerator_tree = None
1294
1316
        revision = _get_one_revision('checkout', revision)
1295
 
        if files_from is not None and files_from != branch_location:
 
1317
        if files_from is not None:
1296
1318
            accelerator_tree = WorkingTree.open(files_from)
1297
1319
        if revision is not None:
1298
1320
            revision_id = revision.as_revision_id(source)
1315
1337
 
1316
1338
 
1317
1339
class cmd_renames(Command):
1318
 
    __doc__ = """Show list of renamed files.
 
1340
    """Show list of renamed files.
1319
1341
    """
1320
1342
    # TODO: Option to show renames between two historical versions.
1321
1343
 
1326
1348
    @display_command
1327
1349
    def run(self, dir=u'.'):
1328
1350
        tree = WorkingTree.open_containing(dir)[0]
1329
 
        self.add_cleanup(tree.lock_read().unlock)
1330
 
        new_inv = tree.inventory
1331
 
        old_tree = tree.basis_tree()
1332
 
        self.add_cleanup(old_tree.lock_read().unlock)
1333
 
        old_inv = old_tree.inventory
1334
 
        renames = []
1335
 
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1336
 
        for f, paths, c, v, p, n, k, e in iterator:
1337
 
            if paths[0] == paths[1]:
1338
 
                continue
1339
 
            if None in (paths):
1340
 
                continue
1341
 
            renames.append(paths)
1342
 
        renames.sort()
1343
 
        for old_name, new_name in renames:
1344
 
            self.outf.write("%s => %s\n" % (old_name, new_name))
 
1351
        tree.lock_read()
 
1352
        try:
 
1353
            new_inv = tree.inventory
 
1354
            old_tree = tree.basis_tree()
 
1355
            old_tree.lock_read()
 
1356
            try:
 
1357
                old_inv = old_tree.inventory
 
1358
                renames = []
 
1359
                iterator = tree.iter_changes(old_tree, include_unchanged=True)
 
1360
                for f, paths, c, v, p, n, k, e in iterator:
 
1361
                    if paths[0] == paths[1]:
 
1362
                        continue
 
1363
                    if None in (paths):
 
1364
                        continue
 
1365
                    renames.append(paths)
 
1366
                renames.sort()
 
1367
                for old_name, new_name in renames:
 
1368
                    self.outf.write("%s => %s\n" % (old_name, new_name))
 
1369
            finally:
 
1370
                old_tree.unlock()
 
1371
        finally:
 
1372
            tree.unlock()
1345
1373
 
1346
1374
 
1347
1375
class cmd_update(Command):
1348
 
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1376
    """Update a tree to have the latest code committed to its branch.
1349
1377
 
1350
1378
    This will perform a merge into the working tree, and may generate
1351
1379
    conflicts. If you have any local changes, you will still
1353
1381
 
1354
1382
    If you want to discard your local changes, you can just do a
1355
1383
    'bzr revert' instead of 'bzr commit' after the update.
1356
 
 
1357
 
    If the tree's branch is bound to a master branch, it will also update
1358
 
    the branch from the master.
1359
1384
    """
1360
1385
 
1361
1386
    _see_also = ['pull', 'working-trees', 'status-flags']
1362
1387
    takes_args = ['dir?']
1363
 
    takes_options = ['revision']
1364
1388
    aliases = ['up']
1365
1389
 
1366
 
    def run(self, dir='.', revision=None):
1367
 
        if revision is not None and len(revision) != 1:
1368
 
            raise errors.BzrCommandError(
1369
 
                        "bzr update --revision takes exactly one revision")
 
1390
    def run(self, dir='.'):
1370
1391
        tree = WorkingTree.open_containing(dir)[0]
1371
 
        branch = tree.branch
1372
1392
        possible_transports = []
1373
 
        master = branch.get_master_branch(
 
1393
        master = tree.branch.get_master_branch(
1374
1394
            possible_transports=possible_transports)
1375
1395
        if master is not None:
1376
 
            branch_location = master.base
1377
1396
            tree.lock_write()
1378
1397
        else:
1379
 
            branch_location = tree.branch.base
1380
1398
            tree.lock_tree_write()
1381
 
        self.add_cleanup(tree.unlock)
1382
 
        # get rid of the final '/' and be ready for display
1383
 
        branch_location = urlutils.unescape_for_display(
1384
 
            branch_location.rstrip('/'),
1385
 
            self.outf.encoding)
1386
 
        existing_pending_merges = tree.get_parent_ids()[1:]
1387
 
        if master is None:
1388
 
            old_tip = None
1389
 
        else:
1390
 
            # may need to fetch data into a heavyweight checkout
1391
 
            # XXX: this may take some time, maybe we should display a
1392
 
            # message
1393
 
            old_tip = branch.update(possible_transports)
1394
 
        if revision is not None:
1395
 
            revision_id = revision[0].as_revision_id(branch)
1396
 
        else:
1397
 
            revision_id = branch.last_revision()
1398
 
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1399
 
            revno = branch.revision_id_to_dotted_revno(revision_id)
1400
 
            note("Tree is up to date at revision %s of branch %s" %
1401
 
                ('.'.join(map(str, revno)), branch_location))
1402
 
            return 0
1403
 
        view_info = _get_view_info_for_change_reporter(tree)
1404
 
        change_reporter = delta._ChangeReporter(
1405
 
            unversioned_filter=tree.is_ignored,
1406
 
            view_info=view_info)
1407
1399
        try:
 
1400
            existing_pending_merges = tree.get_parent_ids()[1:]
 
1401
            last_rev = _mod_revision.ensure_null(tree.last_revision())
 
1402
            if last_rev == _mod_revision.ensure_null(
 
1403
                tree.branch.last_revision()):
 
1404
                # may be up to date, check master too.
 
1405
                if master is None or last_rev == _mod_revision.ensure_null(
 
1406
                    master.last_revision()):
 
1407
                    revno = tree.branch.revision_id_to_revno(last_rev)
 
1408
                    note("Tree is up to date at revision %d." % (revno,))
 
1409
                    return 0
 
1410
            view_info = _get_view_info_for_change_reporter(tree)
1408
1411
            conflicts = tree.update(
1409
 
                change_reporter,
1410
 
                possible_transports=possible_transports,
1411
 
                revision=revision_id,
1412
 
                old_tip=old_tip)
1413
 
        except errors.NoSuchRevision, e:
1414
 
            raise errors.BzrCommandError(
1415
 
                                  "branch has no revision %s\n"
1416
 
                                  "bzr update --revision only works"
1417
 
                                  " for a revision in the branch history"
1418
 
                                  % (e.revision))
1419
 
        revno = tree.branch.revision_id_to_dotted_revno(
1420
 
            _mod_revision.ensure_null(tree.last_revision()))
1421
 
        note('Updated to revision %s of branch %s' %
1422
 
             ('.'.join(map(str, revno)), branch_location))
1423
 
        parent_ids = tree.get_parent_ids()
1424
 
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1425
 
            note('Your local commits will now show as pending merges with '
1426
 
                 "'bzr status', and can be committed with 'bzr commit'.")
1427
 
        if conflicts != 0:
1428
 
            return 1
1429
 
        else:
1430
 
            return 0
 
1412
                delta._ChangeReporter(unversioned_filter=tree.is_ignored,
 
1413
                view_info=view_info), possible_transports=possible_transports)
 
1414
            revno = tree.branch.revision_id_to_revno(
 
1415
                _mod_revision.ensure_null(tree.last_revision()))
 
1416
            note('Updated to revision %d.' % (revno,))
 
1417
            if tree.get_parent_ids()[1:] != existing_pending_merges:
 
1418
                note('Your local commits will now show as pending merges with '
 
1419
                     "'bzr status', and can be committed with 'bzr commit'.")
 
1420
            if conflicts != 0:
 
1421
                return 1
 
1422
            else:
 
1423
                return 0
 
1424
        finally:
 
1425
            tree.unlock()
1431
1426
 
1432
1427
 
1433
1428
class cmd_info(Command):
1434
 
    __doc__ = """Show information about a working tree, branch or repository.
 
1429
    """Show information about a working tree, branch or repository.
1435
1430
 
1436
1431
    This command will show all known locations and formats associated to the
1437
1432
    tree, branch or repository.
1475
1470
 
1476
1471
 
1477
1472
class cmd_remove(Command):
1478
 
    __doc__ = """Remove files or directories.
 
1473
    """Remove files or directories.
1479
1474
 
1480
 
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1481
 
    delete them if they can easily be recovered using revert otherwise they
1482
 
    will be backed up (adding an extention of the form .~#~). If no options or
1483
 
    parameters are given Bazaar will scan for files that are being tracked by
1484
 
    Bazaar but missing in your tree and stop tracking them for you.
 
1475
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1476
    them if they can easily be recovered using revert. If no options or
 
1477
    parameters are given bzr will scan for files that are being tracked by bzr
 
1478
    but missing in your tree and stop tracking them for you.
1485
1479
    """
1486
1480
    takes_args = ['file*']
1487
1481
    takes_options = ['verbose',
1489
1483
        RegistryOption.from_kwargs('file-deletion-strategy',
1490
1484
            'The file deletion mode to be used.',
1491
1485
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1492
 
            safe='Backup changed files (default).',
 
1486
            safe='Only delete files if they can be'
 
1487
                 ' safely recovered (default).',
1493
1488
            keep='Delete from bzr but leave the working copy.',
1494
1489
            force='Delete all the specified files, even if they can not be '
1495
1490
                'recovered and even if they are non-empty directories.')]
1498
1493
 
1499
1494
    def run(self, file_list, verbose=False, new=False,
1500
1495
        file_deletion_strategy='safe'):
1501
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1496
        tree, file_list = tree_files(file_list)
1502
1497
 
1503
1498
        if file_list is not None:
1504
1499
            file_list = [f for f in file_list]
1505
1500
 
1506
 
        self.add_cleanup(tree.lock_write().unlock)
1507
 
        # Heuristics should probably all move into tree.remove_smart or
1508
 
        # some such?
1509
 
        if new:
1510
 
            added = tree.changes_from(tree.basis_tree(),
1511
 
                specific_files=file_list).added
1512
 
            file_list = sorted([f[0] for f in added], reverse=True)
1513
 
            if len(file_list) == 0:
1514
 
                raise errors.BzrCommandError('No matching files.')
1515
 
        elif file_list is None:
1516
 
            # missing files show up in iter_changes(basis) as
1517
 
            # versioned-with-no-kind.
1518
 
            missing = []
1519
 
            for change in tree.iter_changes(tree.basis_tree()):
1520
 
                # Find paths in the working tree that have no kind:
1521
 
                if change[1][1] is not None and change[6][1] is None:
1522
 
                    missing.append(change[1][1])
1523
 
            file_list = sorted(missing, reverse=True)
1524
 
            file_deletion_strategy = 'keep'
1525
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1526
 
            keep_files=file_deletion_strategy=='keep',
1527
 
            force=file_deletion_strategy=='force')
 
1501
        tree.lock_write()
 
1502
        try:
 
1503
            # Heuristics should probably all move into tree.remove_smart or
 
1504
            # some such?
 
1505
            if new:
 
1506
                added = tree.changes_from(tree.basis_tree(),
 
1507
                    specific_files=file_list).added
 
1508
                file_list = sorted([f[0] for f in added], reverse=True)
 
1509
                if len(file_list) == 0:
 
1510
                    raise errors.BzrCommandError('No matching files.')
 
1511
            elif file_list is None:
 
1512
                # missing files show up in iter_changes(basis) as
 
1513
                # versioned-with-no-kind.
 
1514
                missing = []
 
1515
                for change in tree.iter_changes(tree.basis_tree()):
 
1516
                    # Find paths in the working tree that have no kind:
 
1517
                    if change[1][1] is not None and change[6][1] is None:
 
1518
                        missing.append(change[1][1])
 
1519
                file_list = sorted(missing, reverse=True)
 
1520
                file_deletion_strategy = 'keep'
 
1521
            tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1522
                keep_files=file_deletion_strategy=='keep',
 
1523
                force=file_deletion_strategy=='force')
 
1524
        finally:
 
1525
            tree.unlock()
1528
1526
 
1529
1527
 
1530
1528
class cmd_file_id(Command):
1531
 
    __doc__ = """Print file_id of a particular file or directory.
 
1529
    """Print file_id of a particular file or directory.
1532
1530
 
1533
1531
    The file_id is assigned when the file is first added and remains the
1534
1532
    same through all revisions where the file exists, even when it is
1550
1548
 
1551
1549
 
1552
1550
class cmd_file_path(Command):
1553
 
    __doc__ = """Print path of file_ids to a file or directory.
 
1551
    """Print path of file_ids to a file or directory.
1554
1552
 
1555
1553
    This prints one line for each directory down to the target,
1556
1554
    starting at the branch root.
1572
1570
 
1573
1571
 
1574
1572
class cmd_reconcile(Command):
1575
 
    __doc__ = """Reconcile bzr metadata in a branch.
 
1573
    """Reconcile bzr metadata in a branch.
1576
1574
 
1577
1575
    This can correct data mismatches that may have been caused by
1578
1576
    previous ghost operations or bzr upgrades. You should only
1592
1590
 
1593
1591
    _see_also = ['check']
1594
1592
    takes_args = ['branch?']
1595
 
    takes_options = [
1596
 
        Option('canonicalize-chks',
1597
 
               help='Make sure CHKs are in canonical form (repairs '
1598
 
                    'bug 522637).',
1599
 
               hidden=True),
1600
 
        ]
1601
1593
 
1602
 
    def run(self, branch=".", canonicalize_chks=False):
 
1594
    def run(self, branch="."):
1603
1595
        from bzrlib.reconcile import reconcile
1604
1596
        dir = bzrdir.BzrDir.open(branch)
1605
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1597
        reconcile(dir)
1606
1598
 
1607
1599
 
1608
1600
class cmd_revision_history(Command):
1609
 
    __doc__ = """Display the list of revision ids on a branch."""
 
1601
    """Display the list of revision ids on a branch."""
1610
1602
 
1611
1603
    _see_also = ['log']
1612
1604
    takes_args = ['location?']
1622
1614
 
1623
1615
 
1624
1616
class cmd_ancestry(Command):
1625
 
    __doc__ = """List all revisions merged into this branch."""
 
1617
    """List all revisions merged into this branch."""
1626
1618
 
1627
1619
    _see_also = ['log', 'revision-history']
1628
1620
    takes_args = ['location?']
1647
1639
 
1648
1640
 
1649
1641
class cmd_init(Command):
1650
 
    __doc__ = """Make a directory into a versioned branch.
 
1642
    """Make a directory into a versioned branch.
1651
1643
 
1652
1644
    Use this to create an empty branch, or before importing an
1653
1645
    existing project.
1756
1748
 
1757
1749
 
1758
1750
class cmd_init_repository(Command):
1759
 
    __doc__ = """Create a shared repository for branches to share storage space.
 
1751
    """Create a shared repository to hold branches.
1760
1752
 
1761
1753
    New branches created under the repository directory will store their
1762
 
    revisions in the repository, not in the branch directory.  For branches
1763
 
    with shared history, this reduces the amount of storage needed and 
1764
 
    speeds up the creation of new branches.
 
1754
    revisions in the repository, not in the branch directory.
1765
1755
 
1766
 
    If the --no-trees option is given then the branches in the repository
1767
 
    will not have working trees by default.  They will still exist as 
1768
 
    directories on disk, but they will not have separate copies of the 
1769
 
    files at a certain revision.  This can be useful for repositories that
1770
 
    store branches which are interacted with through checkouts or remote
1771
 
    branches, such as on a server.
 
1756
    If the --no-trees option is used then the branches in the repository
 
1757
    will not have working trees by default.
1772
1758
 
1773
1759
    :Examples:
1774
 
        Create a shared repository holding just branches::
 
1760
        Create a shared repositories holding just branches::
1775
1761
 
1776
1762
            bzr init-repo --no-trees repo
1777
1763
            bzr init repo/trunk
1816
1802
 
1817
1803
 
1818
1804
class cmd_diff(Command):
1819
 
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1805
    """Show differences in the working tree, between revisions or branches.
1820
1806
 
1821
1807
    If no arguments are given, all changes for the current tree are listed.
1822
1808
    If files are given, only the changes in those files are listed.
1843
1829
 
1844
1830
            bzr diff -r1
1845
1831
 
1846
 
        Difference between revision 3 and revision 1::
1847
 
 
1848
 
            bzr diff -r1..3
1849
 
 
1850
 
        Difference between revision 3 and revision 1 for branch xxx::
1851
 
 
1852
 
            bzr diff -r1..3 xxx
1853
 
 
1854
 
        To see the changes introduced in revision X::
1855
 
        
1856
 
            bzr diff -cX
1857
 
 
1858
 
        Note that in the case of a merge, the -c option shows the changes
1859
 
        compared to the left hand parent. To see the changes against
1860
 
        another parent, use::
1861
 
 
1862
 
            bzr diff -r<chosen_parent>..X
1863
 
 
1864
 
        The changes introduced by revision 2 (equivalent to -r1..2)::
1865
 
 
1866
 
            bzr diff -c2
 
1832
        Difference between revision 2 and revision 1::
 
1833
 
 
1834
            bzr diff -r1..2
 
1835
 
 
1836
        Difference between revision 2 and revision 1 for branch xxx::
 
1837
 
 
1838
            bzr diff -r1..2 xxx
1867
1839
 
1868
1840
        Show just the differences for file NEWS::
1869
1841
 
1884
1856
        Same as 'bzr diff' but prefix paths with old/ and new/::
1885
1857
 
1886
1858
            bzr diff --prefix old/:new/
1887
 
            
1888
 
        Show the differences using a custom diff program with options::
1889
 
        
1890
 
            bzr diff --using /usr/bin/diff --diff-options -wu
1891
1859
    """
1892
1860
    _see_also = ['status']
1893
1861
    takes_args = ['file*']
1912
1880
            help='Use this command to compare files.',
1913
1881
            type=unicode,
1914
1882
            ),
1915
 
        RegistryOption('format',
1916
 
            help='Diff format to use.',
1917
 
            lazy_registry=('bzrlib.diff', 'format_registry'),
1918
 
            value_switches=False, title='Diff format'),
1919
1883
        ]
1920
1884
    aliases = ['di', 'dif']
1921
1885
    encoding_type = 'exact'
1922
1886
 
1923
1887
    @display_command
1924
1888
    def run(self, revision=None, file_list=None, diff_options=None,
1925
 
            prefix=None, old=None, new=None, using=None, format=None):
1926
 
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
1927
 
            show_diff_trees)
 
1889
            prefix=None, old=None, new=None, using=None):
 
1890
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1928
1891
 
1929
1892
        if (prefix is None) or (prefix == '0'):
1930
1893
            # diff -p0 format
1944
1907
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1945
1908
                                         ' one or two revision specifiers')
1946
1909
 
1947
 
        if using is not None and format is not None:
1948
 
            raise errors.BzrCommandError('--using and --format are mutually '
1949
 
                'exclusive.')
1950
 
 
1951
 
        (old_tree, new_tree,
1952
 
         old_branch, new_branch,
1953
 
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
1954
 
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
1955
 
        # GNU diff on Windows uses ANSI encoding for filenames
1956
 
        path_encoding = osutils.get_diff_header_encoding()
 
1910
        old_tree, new_tree, specific_files, extra_trees = \
 
1911
                _get_trees_to_diff(file_list, revision, old, new,
 
1912
                apply_view=True)
1957
1913
        return show_diff_trees(old_tree, new_tree, sys.stdout,
1958
1914
                               specific_files=specific_files,
1959
1915
                               external_diff_options=diff_options,
1960
1916
                               old_label=old_label, new_label=new_label,
1961
 
                               extra_trees=extra_trees,
1962
 
                               path_encoding=path_encoding,
1963
 
                               using=using,
1964
 
                               format_cls=format)
 
1917
                               extra_trees=extra_trees, using=using)
1965
1918
 
1966
1919
 
1967
1920
class cmd_deleted(Command):
1968
 
    __doc__ = """List files deleted in the working tree.
 
1921
    """List files deleted in the working tree.
1969
1922
    """
1970
1923
    # TODO: Show files deleted since a previous revision, or
1971
1924
    # between two revisions.
1974
1927
    # level of effort but possibly much less IO.  (Or possibly not,
1975
1928
    # if the directories are very large...)
1976
1929
    _see_also = ['status', 'ls']
1977
 
    takes_options = ['directory', 'show-ids']
 
1930
    takes_options = ['show-ids']
1978
1931
 
1979
1932
    @display_command
1980
 
    def run(self, show_ids=False, directory=u'.'):
1981
 
        tree = WorkingTree.open_containing(directory)[0]
1982
 
        self.add_cleanup(tree.lock_read().unlock)
1983
 
        old = tree.basis_tree()
1984
 
        self.add_cleanup(old.lock_read().unlock)
1985
 
        for path, ie in old.inventory.iter_entries():
1986
 
            if not tree.has_id(ie.file_id):
1987
 
                self.outf.write(path)
1988
 
                if show_ids:
1989
 
                    self.outf.write(' ')
1990
 
                    self.outf.write(ie.file_id)
1991
 
                self.outf.write('\n')
 
1933
    def run(self, show_ids=False):
 
1934
        tree = WorkingTree.open_containing(u'.')[0]
 
1935
        tree.lock_read()
 
1936
        try:
 
1937
            old = tree.basis_tree()
 
1938
            old.lock_read()
 
1939
            try:
 
1940
                for path, ie in old.inventory.iter_entries():
 
1941
                    if not tree.has_id(ie.file_id):
 
1942
                        self.outf.write(path)
 
1943
                        if show_ids:
 
1944
                            self.outf.write(' ')
 
1945
                            self.outf.write(ie.file_id)
 
1946
                        self.outf.write('\n')
 
1947
            finally:
 
1948
                old.unlock()
 
1949
        finally:
 
1950
            tree.unlock()
1992
1951
 
1993
1952
 
1994
1953
class cmd_modified(Command):
1995
 
    __doc__ = """List files modified in working tree.
 
1954
    """List files modified in working tree.
1996
1955
    """
1997
1956
 
1998
1957
    hidden = True
1999
1958
    _see_also = ['status', 'ls']
2000
 
    takes_options = ['directory', 'null']
 
1959
    takes_options = [
 
1960
            Option('null',
 
1961
                   help='Write an ascii NUL (\\0) separator '
 
1962
                   'between files rather than a newline.')
 
1963
            ]
2001
1964
 
2002
1965
    @display_command
2003
 
    def run(self, null=False, directory=u'.'):
2004
 
        tree = WorkingTree.open_containing(directory)[0]
 
1966
    def run(self, null=False):
 
1967
        tree = WorkingTree.open_containing(u'.')[0]
2005
1968
        td = tree.changes_from(tree.basis_tree())
2006
1969
        for path, id, kind, text_modified, meta_modified in td.modified:
2007
1970
            if null:
2011
1974
 
2012
1975
 
2013
1976
class cmd_added(Command):
2014
 
    __doc__ = """List files added in working tree.
 
1977
    """List files added in working tree.
2015
1978
    """
2016
1979
 
2017
1980
    hidden = True
2018
1981
    _see_also = ['status', 'ls']
2019
 
    takes_options = ['directory', 'null']
 
1982
    takes_options = [
 
1983
            Option('null',
 
1984
                   help='Write an ascii NUL (\\0) separator '
 
1985
                   'between files rather than a newline.')
 
1986
            ]
2020
1987
 
2021
1988
    @display_command
2022
 
    def run(self, null=False, directory=u'.'):
2023
 
        wt = WorkingTree.open_containing(directory)[0]
2024
 
        self.add_cleanup(wt.lock_read().unlock)
2025
 
        basis = wt.basis_tree()
2026
 
        self.add_cleanup(basis.lock_read().unlock)
2027
 
        basis_inv = basis.inventory
2028
 
        inv = wt.inventory
2029
 
        for file_id in inv:
2030
 
            if file_id in basis_inv:
2031
 
                continue
2032
 
            if inv.is_root(file_id) and len(basis_inv) == 0:
2033
 
                continue
2034
 
            path = inv.id2path(file_id)
2035
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2036
 
                continue
2037
 
            if null:
2038
 
                self.outf.write(path + '\0')
2039
 
            else:
2040
 
                self.outf.write(osutils.quotefn(path) + '\n')
 
1989
    def run(self, null=False):
 
1990
        wt = WorkingTree.open_containing(u'.')[0]
 
1991
        wt.lock_read()
 
1992
        try:
 
1993
            basis = wt.basis_tree()
 
1994
            basis.lock_read()
 
1995
            try:
 
1996
                basis_inv = basis.inventory
 
1997
                inv = wt.inventory
 
1998
                for file_id in inv:
 
1999
                    if file_id in basis_inv:
 
2000
                        continue
 
2001
                    if inv.is_root(file_id) and len(basis_inv) == 0:
 
2002
                        continue
 
2003
                    path = inv.id2path(file_id)
 
2004
                    if not os.access(osutils.abspath(path), os.F_OK):
 
2005
                        continue
 
2006
                    if null:
 
2007
                        self.outf.write(path + '\0')
 
2008
                    else:
 
2009
                        self.outf.write(osutils.quotefn(path) + '\n')
 
2010
            finally:
 
2011
                basis.unlock()
 
2012
        finally:
 
2013
            wt.unlock()
2041
2014
 
2042
2015
 
2043
2016
class cmd_root(Command):
2044
 
    __doc__ = """Show the tree root directory.
 
2017
    """Show the tree root directory.
2045
2018
 
2046
2019
    The root is the nearest enclosing directory with a .bzr control
2047
2020
    directory."""
2071
2044
 
2072
2045
 
2073
2046
class cmd_log(Command):
2074
 
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2047
    """Show historical log for a branch or subset of a branch.
2075
2048
 
2076
2049
    log is bzr's default tool for exploring the history of a branch.
2077
2050
    The branch to use is taken from the first parameter. If no parameters
2188
2161
    :Tips & tricks:
2189
2162
 
2190
2163
      GUI tools and IDEs are often better at exploring history than command
2191
 
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2192
 
      bzr-explorer shell, or the Loggerhead web interface.  See the Plugin
2193
 
      Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2194
 
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
 
2164
      line tools. You may prefer qlog or glog from the QBzr and Bzr-Gtk packages
 
2165
      respectively for example. (TortoiseBzr uses qlog for displaying logs.) See
 
2166
      http://bazaar-vcs.org/BzrPlugins and http://bazaar-vcs.org/IDEIntegration.
 
2167
 
 
2168
      Web interfaces are often better at exploring history than command line
 
2169
      tools, particularly for branches on servers. You may prefer Loggerhead
 
2170
      or one of its alternatives. See http://bazaar-vcs.org/WebInterface.
2195
2171
 
2196
2172
      You may find it useful to add the aliases below to ``bazaar.conf``::
2197
2173
 
2238
2214
                   help='Show just the specified revision.'
2239
2215
                   ' See also "help revisionspec".'),
2240
2216
            'log-format',
2241
 
            RegistryOption('authors',
2242
 
                'What names to list as authors - first, all or committer.',
2243
 
                title='Authors',
2244
 
                lazy_registry=('bzrlib.log', 'author_list_registry'),
2245
 
            ),
2246
2217
            Option('levels',
2247
2218
                   short_name='n',
2248
2219
                   help='Number of levels to display - 0 for all, 1 for flat.',
2263
2234
                   help='Show changes made in each revision as a patch.'),
2264
2235
            Option('include-merges',
2265
2236
                   help='Show merged revisions like --levels 0 does.'),
2266
 
            Option('exclude-common-ancestry',
2267
 
                   help='Display only the revisions that are not part'
2268
 
                   ' of both ancestries (require -rX..Y)'
2269
 
                   )
2270
2237
            ]
2271
2238
    encoding_type = 'replace'
2272
2239
 
2282
2249
            message=None,
2283
2250
            limit=None,
2284
2251
            show_diff=False,
2285
 
            include_merges=False,
2286
 
            authors=None,
2287
 
            exclude_common_ancestry=False,
2288
 
            ):
 
2252
            include_merges=False):
2289
2253
        from bzrlib.log import (
2290
2254
            Logger,
2291
2255
            make_log_request_dict,
2292
2256
            _get_info_for_log_files,
2293
2257
            )
2294
2258
        direction = (forward and 'forward') or 'reverse'
2295
 
        if (exclude_common_ancestry
2296
 
            and (revision is None or len(revision) != 2)):
2297
 
            raise errors.BzrCommandError(
2298
 
                '--exclude-common-ancestry requires -r with two revisions')
2299
2259
        if include_merges:
2300
2260
            if levels is None:
2301
2261
                levels = 0
2314
2274
 
2315
2275
        file_ids = []
2316
2276
        filter_by_dir = False
2317
 
        if file_list:
2318
 
            # find the file ids to log and check for directory filtering
2319
 
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2320
 
                revision, file_list, self.add_cleanup)
2321
 
            for relpath, file_id, kind in file_info_list:
2322
 
                if file_id is None:
2323
 
                    raise errors.BzrCommandError(
2324
 
                        "Path unknown at end or start of revision range: %s" %
2325
 
                        relpath)
2326
 
                # If the relpath is the top of the tree, we log everything
2327
 
                if relpath == '':
2328
 
                    file_ids = []
2329
 
                    break
 
2277
        b = None
 
2278
        try:
 
2279
            if file_list:
 
2280
                # find the file ids to log and check for directory filtering
 
2281
                b, file_info_list, rev1, rev2 = _get_info_for_log_files(
 
2282
                    revision, file_list)
 
2283
                for relpath, file_id, kind in file_info_list:
 
2284
                    if file_id is None:
 
2285
                        raise errors.BzrCommandError(
 
2286
                            "Path unknown at end or start of revision range: %s" %
 
2287
                            relpath)
 
2288
                    # If the relpath is the top of the tree, we log everything
 
2289
                    if relpath == '':
 
2290
                        file_ids = []
 
2291
                        break
 
2292
                    else:
 
2293
                        file_ids.append(file_id)
 
2294
                    filter_by_dir = filter_by_dir or (
 
2295
                        kind in ['directory', 'tree-reference'])
 
2296
            else:
 
2297
                # log everything
 
2298
                # FIXME ? log the current subdir only RBC 20060203
 
2299
                if revision is not None \
 
2300
                        and len(revision) > 0 and revision[0].get_branch():
 
2301
                    location = revision[0].get_branch()
2330
2302
                else:
2331
 
                    file_ids.append(file_id)
2332
 
                filter_by_dir = filter_by_dir or (
2333
 
                    kind in ['directory', 'tree-reference'])
2334
 
        else:
2335
 
            # log everything
2336
 
            # FIXME ? log the current subdir only RBC 20060203
2337
 
            if revision is not None \
2338
 
                    and len(revision) > 0 and revision[0].get_branch():
2339
 
                location = revision[0].get_branch()
2340
 
            else:
2341
 
                location = '.'
2342
 
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2343
 
            b = dir.open_branch()
2344
 
            self.add_cleanup(b.lock_read().unlock)
2345
 
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2346
 
 
2347
 
        # Decide on the type of delta & diff filtering to use
2348
 
        # TODO: add an --all-files option to make this configurable & consistent
2349
 
        if not verbose:
2350
 
            delta_type = None
2351
 
        else:
2352
 
            delta_type = 'full'
2353
 
        if not show_diff:
2354
 
            diff_type = None
2355
 
        elif file_ids:
2356
 
            diff_type = 'partial'
2357
 
        else:
2358
 
            diff_type = 'full'
2359
 
 
2360
 
        # Build the log formatter
2361
 
        if log_format is None:
2362
 
            log_format = log.log_formatter_registry.get_default(b)
2363
 
        # Make a non-encoding output to include the diffs - bug 328007
2364
 
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2365
 
        lf = log_format(show_ids=show_ids, to_file=self.outf,
2366
 
                        to_exact_file=unencoded_output,
2367
 
                        show_timezone=timezone,
2368
 
                        delta_format=get_verbosity_level(),
2369
 
                        levels=levels,
2370
 
                        show_advice=levels is None,
2371
 
                        author_list_handler=authors)
2372
 
 
2373
 
        # Choose the algorithm for doing the logging. It's annoying
2374
 
        # having multiple code paths like this but necessary until
2375
 
        # the underlying repository format is faster at generating
2376
 
        # deltas or can provide everything we need from the indices.
2377
 
        # The default algorithm - match-using-deltas - works for
2378
 
        # multiple files and directories and is faster for small
2379
 
        # amounts of history (200 revisions say). However, it's too
2380
 
        # slow for logging a single file in a repository with deep
2381
 
        # history, i.e. > 10K revisions. In the spirit of "do no
2382
 
        # evil when adding features", we continue to use the
2383
 
        # original algorithm - per-file-graph - for the "single
2384
 
        # file that isn't a directory without showing a delta" case.
2385
 
        partial_history = revision and b.repository._format.supports_chks
2386
 
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2387
 
            or delta_type or partial_history)
2388
 
 
2389
 
        # Build the LogRequest and execute it
2390
 
        if len(file_ids) == 0:
2391
 
            file_ids = None
2392
 
        rqst = make_log_request_dict(
2393
 
            direction=direction, specific_fileids=file_ids,
2394
 
            start_revision=rev1, end_revision=rev2, limit=limit,
2395
 
            message_search=message, delta_type=delta_type,
2396
 
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2397
 
            exclude_common_ancestry=exclude_common_ancestry,
2398
 
            )
2399
 
        Logger(b, rqst).show(lf)
 
2303
                    location = '.'
 
2304
                dir, relpath = bzrdir.BzrDir.open_containing(location)
 
2305
                b = dir.open_branch()
 
2306
                b.lock_read()
 
2307
                rev1, rev2 = _get_revision_range(revision, b, self.name())
 
2308
 
 
2309
            # Decide on the type of delta & diff filtering to use
 
2310
            # TODO: add an --all-files option to make this configurable & consistent
 
2311
            if not verbose:
 
2312
                delta_type = None
 
2313
            else:
 
2314
                delta_type = 'full'
 
2315
            if not show_diff:
 
2316
                diff_type = None
 
2317
            elif file_ids:
 
2318
                diff_type = 'partial'
 
2319
            else:
 
2320
                diff_type = 'full'
 
2321
 
 
2322
            # Build the log formatter
 
2323
            if log_format is None:
 
2324
                log_format = log.log_formatter_registry.get_default(b)
 
2325
            lf = log_format(show_ids=show_ids, to_file=self.outf,
 
2326
                            show_timezone=timezone,
 
2327
                            delta_format=get_verbosity_level(),
 
2328
                            levels=levels,
 
2329
                            show_advice=levels is None)
 
2330
 
 
2331
            # Choose the algorithm for doing the logging. It's annoying
 
2332
            # having multiple code paths like this but necessary until
 
2333
            # the underlying repository format is faster at generating
 
2334
            # deltas or can provide everything we need from the indices.
 
2335
            # The default algorithm - match-using-deltas - works for
 
2336
            # multiple files and directories and is faster for small
 
2337
            # amounts of history (200 revisions say). However, it's too
 
2338
            # slow for logging a single file in a repository with deep
 
2339
            # history, i.e. > 10K revisions. In the spirit of "do no
 
2340
            # evil when adding features", we continue to use the
 
2341
            # original algorithm - per-file-graph - for the "single
 
2342
            # file that isn't a directory without showing a delta" case.
 
2343
            partial_history = revision and b.repository._format.supports_chks
 
2344
            match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2345
                or delta_type or partial_history)
 
2346
 
 
2347
            # Build the LogRequest and execute it
 
2348
            if len(file_ids) == 0:
 
2349
                file_ids = None
 
2350
            rqst = make_log_request_dict(
 
2351
                direction=direction, specific_fileids=file_ids,
 
2352
                start_revision=rev1, end_revision=rev2, limit=limit,
 
2353
                message_search=message, delta_type=delta_type,
 
2354
                diff_type=diff_type, _match_using_deltas=match_using_deltas)
 
2355
            Logger(b, rqst).show(lf)
 
2356
        finally:
 
2357
            if b is not None:
 
2358
                b.unlock()
2400
2359
 
2401
2360
 
2402
2361
def _get_revision_range(revisionspec_list, branch, command_name):
2420
2379
            raise errors.BzrCommandError(
2421
2380
                "bzr %s doesn't accept two revisions in different"
2422
2381
                " branches." % command_name)
2423
 
        if start_spec.spec is None:
2424
 
            # Avoid loading all the history.
2425
 
            rev1 = RevisionInfo(branch, None, None)
2426
 
        else:
2427
 
            rev1 = start_spec.in_history(branch)
 
2382
        rev1 = start_spec.in_history(branch)
2428
2383
        # Avoid loading all of history when we know a missing
2429
2384
        # end of range means the last revision ...
2430
2385
        if end_spec.spec is None:
2459
2414
 
2460
2415
 
2461
2416
class cmd_touching_revisions(Command):
2462
 
    __doc__ = """Return revision-ids which affected a particular file.
 
2417
    """Return revision-ids which affected a particular file.
2463
2418
 
2464
2419
    A more user-friendly interface is "bzr log FILE".
2465
2420
    """
2472
2427
        tree, relpath = WorkingTree.open_containing(filename)
2473
2428
        file_id = tree.path2id(relpath)
2474
2429
        b = tree.branch
2475
 
        self.add_cleanup(b.lock_read().unlock)
2476
 
        touching_revs = log.find_touching_revisions(b, file_id)
2477
 
        for revno, revision_id, what in touching_revs:
2478
 
            self.outf.write("%6d %s\n" % (revno, what))
 
2430
        b.lock_read()
 
2431
        try:
 
2432
            touching_revs = log.find_touching_revisions(b, file_id)
 
2433
            for revno, revision_id, what in touching_revs:
 
2434
                self.outf.write("%6d %s\n" % (revno, what))
 
2435
        finally:
 
2436
            b.unlock()
2479
2437
 
2480
2438
 
2481
2439
class cmd_ls(Command):
2482
 
    __doc__ = """List files in a tree.
 
2440
    """List files in a tree.
2483
2441
    """
2484
2442
 
2485
2443
    _see_also = ['status', 'cat']
2491
2449
                   help='Recurse into subdirectories.'),
2492
2450
            Option('from-root',
2493
2451
                   help='Print paths relative to the root of the branch.'),
2494
 
            Option('unknown', short_name='u',
2495
 
                help='Print unknown files.'),
 
2452
            Option('unknown', help='Print unknown files.'),
2496
2453
            Option('versioned', help='Print versioned files.',
2497
2454
                   short_name='V'),
2498
 
            Option('ignored', short_name='i',
2499
 
                help='Print ignored files.'),
2500
 
            Option('kind', short_name='k',
 
2455
            Option('ignored', help='Print ignored files.'),
 
2456
            Option('null',
 
2457
                   help='Write an ascii NUL (\\0) separator '
 
2458
                   'between files rather than a newline.'),
 
2459
            Option('kind',
2501
2460
                   help='List entries of a particular kind: file, directory, symlink.',
2502
2461
                   type=unicode),
2503
 
            'null',
2504
2462
            'show-ids',
2505
 
            'directory',
2506
2463
            ]
2507
2464
    @display_command
2508
2465
    def run(self, revision=None, verbose=False,
2509
2466
            recursive=False, from_root=False,
2510
2467
            unknown=False, versioned=False, ignored=False,
2511
 
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2468
            null=False, kind=None, show_ids=False, path=None):
2512
2469
 
2513
2470
        if kind and kind not in ('file', 'directory', 'symlink'):
2514
2471
            raise errors.BzrCommandError('invalid kind specified')
2526
2483
                raise errors.BzrCommandError('cannot specify both --from-root'
2527
2484
                                             ' and PATH')
2528
2485
            fs_path = path
2529
 
        tree, branch, relpath = \
2530
 
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2486
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2487
            fs_path)
2531
2488
 
2532
2489
        # Calculate the prefix to use
2533
2490
        prefix = None
2534
2491
        if from_root:
2535
2492
            if relpath:
2536
2493
                prefix = relpath + '/'
2537
 
        elif fs_path != '.' and not fs_path.endswith('/'):
 
2494
        elif fs_path != '.':
2538
2495
            prefix = fs_path + '/'
2539
2496
 
2540
2497
        if revision is not None or tree is None:
2548
2505
                view_str = views.view_display_str(view_files)
2549
2506
                note("Ignoring files outside view. View is %s" % view_str)
2550
2507
 
2551
 
        self.add_cleanup(tree.lock_read().unlock)
2552
 
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2553
 
            from_dir=relpath, recursive=recursive):
2554
 
            # Apply additional masking
2555
 
            if not all and not selection[fc]:
2556
 
                continue
2557
 
            if kind is not None and fkind != kind:
2558
 
                continue
2559
 
            if apply_view:
2560
 
                try:
2561
 
                    if relpath:
2562
 
                        fullpath = osutils.pathjoin(relpath, fp)
2563
 
                    else:
2564
 
                        fullpath = fp
2565
 
                    views.check_path_in_view(tree, fullpath)
2566
 
                except errors.FileOutsideView:
2567
 
                    continue
 
2508
        tree.lock_read()
 
2509
        try:
 
2510
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
2511
                from_dir=relpath, recursive=recursive):
 
2512
                # Apply additional masking
 
2513
                if not all and not selection[fc]:
 
2514
                    continue
 
2515
                if kind is not None and fkind != kind:
 
2516
                    continue
 
2517
                if apply_view:
 
2518
                    try:
 
2519
                        if relpath:
 
2520
                            fullpath = osutils.pathjoin(relpath, fp)
 
2521
                        else:
 
2522
                            fullpath = fp
 
2523
                        views.check_path_in_view(tree, fullpath)
 
2524
                    except errors.FileOutsideView:
 
2525
                        continue
2568
2526
 
2569
 
            # Output the entry
2570
 
            if prefix:
2571
 
                fp = osutils.pathjoin(prefix, fp)
2572
 
            kindch = entry.kind_character()
2573
 
            outstring = fp + kindch
2574
 
            ui.ui_factory.clear_term()
2575
 
            if verbose:
2576
 
                outstring = '%-8s %s' % (fc, outstring)
2577
 
                if show_ids and fid is not None:
2578
 
                    outstring = "%-50s %s" % (outstring, fid)
2579
 
                self.outf.write(outstring + '\n')
2580
 
            elif null:
2581
 
                self.outf.write(fp + '\0')
2582
 
                if show_ids:
2583
 
                    if fid is not None:
2584
 
                        self.outf.write(fid)
2585
 
                    self.outf.write('\0')
2586
 
                self.outf.flush()
2587
 
            else:
2588
 
                if show_ids:
2589
 
                    if fid is not None:
2590
 
                        my_id = fid
2591
 
                    else:
2592
 
                        my_id = ''
2593
 
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
2594
 
                else:
 
2527
                # Output the entry
 
2528
                if prefix:
 
2529
                    fp = osutils.pathjoin(prefix, fp)
 
2530
                kindch = entry.kind_character()
 
2531
                outstring = fp + kindch
 
2532
                ui.ui_factory.clear_term()
 
2533
                if verbose:
 
2534
                    outstring = '%-8s %s' % (fc, outstring)
 
2535
                    if show_ids and fid is not None:
 
2536
                        outstring = "%-50s %s" % (outstring, fid)
2595
2537
                    self.outf.write(outstring + '\n')
 
2538
                elif null:
 
2539
                    self.outf.write(fp + '\0')
 
2540
                    if show_ids:
 
2541
                        if fid is not None:
 
2542
                            self.outf.write(fid)
 
2543
                        self.outf.write('\0')
 
2544
                    self.outf.flush()
 
2545
                else:
 
2546
                    if show_ids:
 
2547
                        if fid is not None:
 
2548
                            my_id = fid
 
2549
                        else:
 
2550
                            my_id = ''
 
2551
                        self.outf.write('%-50s %s\n' % (outstring, my_id))
 
2552
                    else:
 
2553
                        self.outf.write(outstring + '\n')
 
2554
        finally:
 
2555
            tree.unlock()
2596
2556
 
2597
2557
 
2598
2558
class cmd_unknowns(Command):
2599
 
    __doc__ = """List unknown files.
 
2559
    """List unknown files.
2600
2560
    """
2601
2561
 
2602
2562
    hidden = True
2603
2563
    _see_also = ['ls']
2604
 
    takes_options = ['directory']
2605
2564
 
2606
2565
    @display_command
2607
 
    def run(self, directory=u'.'):
2608
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
2566
    def run(self):
 
2567
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
2609
2568
            self.outf.write(osutils.quotefn(f) + '\n')
2610
2569
 
2611
2570
 
2612
2571
class cmd_ignore(Command):
2613
 
    __doc__ = """Ignore specified files or patterns.
 
2572
    """Ignore specified files or patterns.
2614
2573
 
2615
2574
    See ``bzr help patterns`` for details on the syntax of patterns.
2616
2575
 
2617
 
    If a .bzrignore file does not exist, the ignore command
2618
 
    will create one and add the specified files or patterns to the newly
2619
 
    created file. The ignore command will also automatically add the 
2620
 
    .bzrignore file to be versioned. Creating a .bzrignore file without
2621
 
    the use of the ignore command will require an explicit add command.
2622
 
 
2623
2576
    To remove patterns from the ignore list, edit the .bzrignore file.
2624
2577
    After adding, editing or deleting that file either indirectly by
2625
2578
    using this command or directly by using an editor, be sure to commit
2626
2579
    it.
2627
 
    
2628
 
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2629
 
    the global ignore file can be found in the application data directory as
2630
 
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2631
 
    Global ignores are not touched by this command. The global ignore file
2632
 
    can be edited directly using an editor.
2633
 
 
2634
 
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2635
 
    precedence over regular ignores.  Such exceptions are used to specify
2636
 
    files that should be versioned which would otherwise be ignored.
2637
 
    
2638
 
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2639
 
    precedence over the '!' exception patterns.
2640
2580
 
2641
2581
    Note: ignore patterns containing shell wildcards must be quoted from
2642
2582
    the shell on Unix.
2646
2586
 
2647
2587
            bzr ignore ./Makefile
2648
2588
 
2649
 
        Ignore .class files in all directories...::
 
2589
        Ignore class files in all directories::
2650
2590
 
2651
2591
            bzr ignore "*.class"
2652
2592
 
2653
 
        ...but do not ignore "special.class"::
2654
 
 
2655
 
            bzr ignore "!special.class"
2656
 
 
2657
2593
        Ignore .o files under the lib directory::
2658
2594
 
2659
2595
            bzr ignore "lib/**/*.o"
2665
2601
        Ignore everything but the "debian" toplevel directory::
2666
2602
 
2667
2603
            bzr ignore "RE:(?!debian/).*"
2668
 
        
2669
 
        Ignore everything except the "local" toplevel directory,
2670
 
        but always ignore "*~" autosave files, even under local/::
2671
 
        
2672
 
            bzr ignore "*"
2673
 
            bzr ignore "!./local"
2674
 
            bzr ignore "!!*~"
2675
2604
    """
2676
2605
 
2677
2606
    _see_also = ['status', 'ignored', 'patterns']
2678
2607
    takes_args = ['name_pattern*']
2679
 
    takes_options = ['directory',
2680
 
        Option('default-rules',
2681
 
               help='Display the default ignore rules that bzr uses.')
 
2608
    takes_options = [
 
2609
        Option('old-default-rules',
 
2610
               help='Write out the ignore rules bzr < 0.9 always used.')
2682
2611
        ]
2683
2612
 
2684
 
    def run(self, name_pattern_list=None, default_rules=None,
2685
 
            directory=u'.'):
 
2613
    def run(self, name_pattern_list=None, old_default_rules=None):
2686
2614
        from bzrlib import ignores
2687
 
        if default_rules is not None:
2688
 
            # dump the default rules and exit
2689
 
            for pattern in ignores.USER_DEFAULTS:
2690
 
                self.outf.write("%s\n" % pattern)
 
2615
        if old_default_rules is not None:
 
2616
            # dump the rules and exit
 
2617
            for pattern in ignores.OLD_DEFAULTS:
 
2618
                print pattern
2691
2619
            return
2692
2620
        if not name_pattern_list:
2693
2621
            raise errors.BzrCommandError("ignore requires at least one "
2694
 
                "NAME_PATTERN or --default-rules.")
 
2622
                                  "NAME_PATTERN or --old-default-rules")
2695
2623
        name_pattern_list = [globbing.normalize_pattern(p)
2696
2624
                             for p in name_pattern_list]
2697
 
        bad_patterns = ''
2698
 
        for p in name_pattern_list:
2699
 
            if not globbing.Globster.is_pattern_valid(p):
2700
 
                bad_patterns += ('\n  %s' % p)
2701
 
        if bad_patterns:
2702
 
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2703
 
            ui.ui_factory.show_error(msg)
2704
 
            raise errors.InvalidPattern('')
2705
2625
        for name_pattern in name_pattern_list:
2706
2626
            if (name_pattern[0] == '/' or
2707
2627
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2708
2628
                raise errors.BzrCommandError(
2709
2629
                    "NAME_PATTERN should not be an absolute path")
2710
 
        tree, relpath = WorkingTree.open_containing(directory)
 
2630
        tree, relpath = WorkingTree.open_containing(u'.')
2711
2631
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2712
2632
        ignored = globbing.Globster(name_pattern_list)
2713
2633
        matches = []
2714
 
        self.add_cleanup(tree.lock_read().unlock)
 
2634
        tree.lock_read()
2715
2635
        for entry in tree.list_files():
2716
2636
            id = entry[3]
2717
2637
            if id is not None:
2718
2638
                filename = entry[0]
2719
2639
                if ignored.match(filename):
2720
 
                    matches.append(filename)
 
2640
                    matches.append(filename.encode('utf-8'))
 
2641
        tree.unlock()
2721
2642
        if len(matches) > 0:
2722
 
            self.outf.write("Warning: the following files are version controlled and"
2723
 
                  " match your ignore pattern:\n%s"
2724
 
                  "\nThese files will continue to be version controlled"
2725
 
                  " unless you 'bzr remove' them.\n" % ("\n".join(matches),))
 
2643
            print "Warning: the following files are version controlled and" \
 
2644
                  " match your ignore pattern:\n%s" \
 
2645
                  "\nThese files will continue to be version controlled" \
 
2646
                  " unless you 'bzr remove' them." % ("\n".join(matches),)
2726
2647
 
2727
2648
 
2728
2649
class cmd_ignored(Command):
2729
 
    __doc__ = """List ignored files and the patterns that matched them.
 
2650
    """List ignored files and the patterns that matched them.
2730
2651
 
2731
2652
    List all the ignored files and the ignore pattern that caused the file to
2732
2653
    be ignored.
2738
2659
 
2739
2660
    encoding_type = 'replace'
2740
2661
    _see_also = ['ignore', 'ls']
2741
 
    takes_options = ['directory']
2742
2662
 
2743
2663
    @display_command
2744
 
    def run(self, directory=u'.'):
2745
 
        tree = WorkingTree.open_containing(directory)[0]
2746
 
        self.add_cleanup(tree.lock_read().unlock)
2747
 
        for path, file_class, kind, file_id, entry in tree.list_files():
2748
 
            if file_class != 'I':
2749
 
                continue
2750
 
            ## XXX: Slightly inefficient since this was already calculated
2751
 
            pat = tree.is_ignored(path)
2752
 
            self.outf.write('%-50s %s\n' % (path, pat))
 
2664
    def run(self):
 
2665
        tree = WorkingTree.open_containing(u'.')[0]
 
2666
        tree.lock_read()
 
2667
        try:
 
2668
            for path, file_class, kind, file_id, entry in tree.list_files():
 
2669
                if file_class != 'I':
 
2670
                    continue
 
2671
                ## XXX: Slightly inefficient since this was already calculated
 
2672
                pat = tree.is_ignored(path)
 
2673
                self.outf.write('%-50s %s\n' % (path, pat))
 
2674
        finally:
 
2675
            tree.unlock()
2753
2676
 
2754
2677
 
2755
2678
class cmd_lookup_revision(Command):
2756
 
    __doc__ = """Lookup the revision-id from a revision-number
 
2679
    """Lookup the revision-id from a revision-number
2757
2680
 
2758
2681
    :Examples:
2759
2682
        bzr lookup-revision 33
2760
2683
    """
2761
2684
    hidden = True
2762
2685
    takes_args = ['revno']
2763
 
    takes_options = ['directory']
2764
2686
 
2765
2687
    @display_command
2766
 
    def run(self, revno, directory=u'.'):
 
2688
    def run(self, revno):
2767
2689
        try:
2768
2690
            revno = int(revno)
2769
2691
        except ValueError:
2770
 
            raise errors.BzrCommandError("not a valid revision-number: %r"
2771
 
                                         % revno)
2772
 
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2773
 
        self.outf.write("%s\n" % revid)
 
2692
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
 
2693
 
 
2694
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2774
2695
 
2775
2696
 
2776
2697
class cmd_export(Command):
2777
 
    __doc__ = """Export current or past revision to a destination directory or archive.
 
2698
    """Export current or past revision to a destination directory or archive.
2778
2699
 
2779
2700
    If no revision is specified this exports the last committed revision.
2780
2701
 
2802
2723
      =================       =========================
2803
2724
    """
2804
2725
    takes_args = ['dest', 'branch_or_subdir?']
2805
 
    takes_options = ['directory',
 
2726
    takes_options = [
2806
2727
        Option('format',
2807
2728
               help="Type of file to export to.",
2808
2729
               type=unicode),
2812
2733
        Option('root',
2813
2734
               type=str,
2814
2735
               help="Name of the root directory inside the exported file."),
2815
 
        Option('per-file-timestamps',
2816
 
               help='Set modification time of files to that of the last '
2817
 
                    'revision in which it was changed.'),
2818
2736
        ]
2819
2737
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2820
 
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
 
2738
        root=None, filters=False):
2821
2739
        from bzrlib.export import export
2822
2740
 
2823
2741
        if branch_or_subdir is None:
2824
 
            tree = WorkingTree.open_containing(directory)[0]
 
2742
            tree = WorkingTree.open_containing(u'.')[0]
2825
2743
            b = tree.branch
2826
2744
            subdir = None
2827
2745
        else:
2830
2748
 
2831
2749
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2832
2750
        try:
2833
 
            export(rev_tree, dest, format, root, subdir, filtered=filters,
2834
 
                   per_file_timestamps=per_file_timestamps)
 
2751
            export(rev_tree, dest, format, root, subdir, filtered=filters)
2835
2752
        except errors.NoSuchExportFormat, e:
2836
2753
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2837
2754
 
2838
2755
 
2839
2756
class cmd_cat(Command):
2840
 
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
2757
    """Write the contents of a file as of a given revision to standard output.
2841
2758
 
2842
2759
    If no revision is nominated, the last revision is used.
2843
2760
 
2846
2763
    """
2847
2764
 
2848
2765
    _see_also = ['ls']
2849
 
    takes_options = ['directory',
 
2766
    takes_options = [
2850
2767
        Option('name-from-revision', help='The path name in the old tree.'),
2851
2768
        Option('filters', help='Apply content filters to display the '
2852
2769
                'convenience form.'),
2857
2774
 
2858
2775
    @display_command
2859
2776
    def run(self, filename, revision=None, name_from_revision=False,
2860
 
            filters=False, directory=None):
 
2777
            filters=False):
2861
2778
        if revision is not None and len(revision) != 1:
2862
2779
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2863
2780
                                         " one revision specifier")
2864
2781
        tree, branch, relpath = \
2865
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
2866
 
        self.add_cleanup(branch.lock_read().unlock)
2867
 
        return self._run(tree, branch, relpath, filename, revision,
2868
 
                         name_from_revision, filters)
 
2782
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2783
        branch.lock_read()
 
2784
        try:
 
2785
            return self._run(tree, branch, relpath, filename, revision,
 
2786
                             name_from_revision, filters)
 
2787
        finally:
 
2788
            branch.unlock()
2869
2789
 
2870
2790
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2871
2791
        filtered):
2872
2792
        if tree is None:
2873
2793
            tree = b.basis_tree()
2874
2794
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2875
 
        self.add_cleanup(rev_tree.lock_read().unlock)
2876
2795
 
2877
2796
        old_file_id = rev_tree.path2id(relpath)
2878
2797
 
2913
2832
            chunks = content.splitlines(True)
2914
2833
            content = filtered_output_bytes(chunks, filters,
2915
2834
                ContentFilterContext(relpath, rev_tree))
2916
 
            self.cleanup_now()
2917
2835
            self.outf.writelines(content)
2918
2836
        else:
2919
 
            self.cleanup_now()
2920
2837
            self.outf.write(content)
2921
2838
 
2922
2839
 
2923
2840
class cmd_local_time_offset(Command):
2924
 
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
2841
    """Show the offset in seconds from GMT to local time."""
2925
2842
    hidden = True
2926
2843
    @display_command
2927
2844
    def run(self):
2928
 
        self.outf.write("%s\n" % osutils.local_time_offset())
 
2845
        print osutils.local_time_offset()
2929
2846
 
2930
2847
 
2931
2848
 
2932
2849
class cmd_commit(Command):
2933
 
    __doc__ = """Commit changes into a new revision.
 
2850
    """Commit changes into a new revision.
2934
2851
 
2935
2852
    An explanatory message needs to be given for each commit. This is
2936
2853
    often done by using the --message option (getting the message from the
3029
2946
             Option('strict',
3030
2947
                    help="Refuse to commit if there are unknown "
3031
2948
                    "files in the working tree."),
3032
 
             Option('commit-time', type=str,
3033
 
                    help="Manually set a commit time using commit date "
3034
 
                    "format, e.g. '2009-10-10 08:00:00 +0100'."),
3035
2949
             ListOption('fixes', type=str,
3036
2950
                    help="Mark a bug as being fixed by this revision "
3037
2951
                         "(see \"bzr help bugs\")."),
3044
2958
                         "the master branch until a normal commit "
3045
2959
                         "is performed."
3046
2960
                    ),
3047
 
             Option('show-diff', short_name='p',
3048
 
                    help='When no message is supplied, show the diff along'
3049
 
                    ' with the status summary in the message editor.'),
 
2961
              Option('show-diff',
 
2962
                     help='When no message is supplied, show the diff along'
 
2963
                     ' with the status summary in the message editor.'),
3050
2964
             ]
3051
2965
    aliases = ['ci', 'checkin']
3052
2966
 
3071
2985
 
3072
2986
    def run(self, message=None, file=None, verbose=False, selected_list=None,
3073
2987
            unchanged=False, strict=False, local=False, fixes=None,
3074
 
            author=None, show_diff=False, exclude=None, commit_time=None):
 
2988
            author=None, show_diff=False, exclude=None):
3075
2989
        from bzrlib.errors import (
3076
2990
            PointlessCommit,
3077
2991
            ConflictsInTree,
3083
2997
            make_commit_message_template_encoded
3084
2998
        )
3085
2999
 
3086
 
        commit_stamp = offset = None
3087
 
        if commit_time is not None:
3088
 
            try:
3089
 
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3090
 
            except ValueError, e:
3091
 
                raise errors.BzrCommandError(
3092
 
                    "Could not parse --commit-time: " + str(e))
3093
 
 
3094
3000
        # TODO: Need a blackbox test for invoking the external editor; may be
3095
3001
        # slightly problematic to run this cross-platform.
3096
3002
 
3099
3005
 
3100
3006
        properties = {}
3101
3007
 
3102
 
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
3008
        tree, selected_list = tree_files(selected_list)
3103
3009
        if selected_list == ['']:
3104
3010
            # workaround - commit of root of tree should be exactly the same
3105
3011
            # as just default commit in that tree, and succeed even though
3116
3022
        if local and not tree.branch.get_bound_location():
3117
3023
            raise errors.LocalRequiresBoundBranch()
3118
3024
 
3119
 
        if message is not None:
3120
 
            try:
3121
 
                file_exists = osutils.lexists(message)
3122
 
            except UnicodeError:
3123
 
                # The commit message contains unicode characters that can't be
3124
 
                # represented in the filesystem encoding, so that can't be a
3125
 
                # file.
3126
 
                file_exists = False
3127
 
            if file_exists:
3128
 
                warning_msg = (
3129
 
                    'The commit message is a file name: "%(f)s".\n'
3130
 
                    '(use --file "%(f)s" to take commit message from that file)'
3131
 
                    % { 'f': message })
3132
 
                ui.ui_factory.show_warning(warning_msg)
3133
 
            if '\r' in message:
3134
 
                message = message.replace('\r\n', '\n')
3135
 
                message = message.replace('\r', '\n')
3136
 
            if file:
3137
 
                raise errors.BzrCommandError(
3138
 
                    "please specify either --message or --file")
3139
 
 
3140
3025
        def get_message(commit_obj):
3141
3026
            """Callback to get commit message"""
3142
 
            if file:
3143
 
                f = open(file)
3144
 
                try:
3145
 
                    my_message = f.read().decode(osutils.get_user_encoding())
3146
 
                finally:
3147
 
                    f.close()
3148
 
            elif message is not None:
3149
 
                my_message = message
3150
 
            else:
3151
 
                # No message supplied: make one up.
3152
 
                # text is the status of the tree
3153
 
                text = make_commit_message_template_encoded(tree,
 
3027
            my_message = message
 
3028
            if my_message is None and not file:
 
3029
                t = make_commit_message_template_encoded(tree,
3154
3030
                        selected_list, diff=show_diff,
3155
3031
                        output_encoding=osutils.get_user_encoding())
3156
 
                # start_message is the template generated from hooks
3157
 
                # XXX: Warning - looks like hooks return unicode,
3158
 
                # make_commit_message_template_encoded returns user encoding.
3159
 
                # We probably want to be using edit_commit_message instead to
3160
 
                # avoid this.
3161
3032
                start_message = generate_commit_message_template(commit_obj)
3162
 
                my_message = edit_commit_message_encoded(text,
 
3033
                my_message = edit_commit_message_encoded(t,
3163
3034
                    start_message=start_message)
3164
3035
                if my_message is None:
3165
3036
                    raise errors.BzrCommandError("please specify a commit"
3166
3037
                        " message with either --message or --file")
 
3038
            elif my_message and file:
 
3039
                raise errors.BzrCommandError(
 
3040
                    "please specify either --message or --file")
 
3041
            if file:
 
3042
                my_message = codecs.open(file, 'rt',
 
3043
                                         osutils.get_user_encoding()).read()
3167
3044
            if my_message == "":
3168
3045
                raise errors.BzrCommandError("empty commit message specified")
3169
3046
            return my_message
3177
3054
                        specific_files=selected_list,
3178
3055
                        allow_pointless=unchanged, strict=strict, local=local,
3179
3056
                        reporter=None, verbose=verbose, revprops=properties,
3180
 
                        authors=author, timestamp=commit_stamp,
3181
 
                        timezone=offset,
3182
 
                        exclude=tree.safe_relpath_files(exclude))
 
3057
                        authors=author,
 
3058
                        exclude=safe_relpath_files(tree, exclude))
3183
3059
        except PointlessCommit:
 
3060
            # FIXME: This should really happen before the file is read in;
 
3061
            # perhaps prepare the commit; get the message; then actually commit
3184
3062
            raise errors.BzrCommandError("No changes to commit."
3185
3063
                              " Use --unchanged to commit anyhow.")
3186
3064
        except ConflictsInTree:
3191
3069
            raise errors.BzrCommandError("Commit refused because there are"
3192
3070
                              " unknown files in the working tree.")
3193
3071
        except errors.BoundBranchOutOfDate, e:
3194
 
            e.extra_help = ("\n"
3195
 
                'To commit to master branch, run update and then commit.\n'
3196
 
                'You can also pass --local to commit to continue working '
3197
 
                'disconnected.')
3198
 
            raise
 
3072
            raise errors.BzrCommandError(str(e) + "\n"
 
3073
            'To commit to master branch, run update and then commit.\n'
 
3074
            'You can also pass --local to commit to continue working '
 
3075
            'disconnected.')
3199
3076
 
3200
3077
 
3201
3078
class cmd_check(Command):
3202
 
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3079
    """Validate working tree structure, branch consistency and repository history.
3203
3080
 
3204
3081
    This command checks various invariants about branch and repository storage
3205
3082
    to detect data corruption or bzr bugs.
3269
3146
 
3270
3147
 
3271
3148
class cmd_upgrade(Command):
3272
 
    __doc__ = """Upgrade branch storage to current format.
 
3149
    """Upgrade branch storage to current format.
3273
3150
 
3274
3151
    The check command or bzr developers may sometimes advise you to run
3275
3152
    this command. When the default format has changed you may also be warned
3293
3170
 
3294
3171
 
3295
3172
class cmd_whoami(Command):
3296
 
    __doc__ = """Show or set bzr user id.
 
3173
    """Show or set bzr user id.
3297
3174
 
3298
3175
    :Examples:
3299
3176
        Show the email of the current user::
3304
3181
 
3305
3182
            bzr whoami "Frank Chu <fchu@example.com>"
3306
3183
    """
3307
 
    takes_options = [ 'directory',
3308
 
                      Option('email',
 
3184
    takes_options = [ Option('email',
3309
3185
                             help='Display email address only.'),
3310
3186
                      Option('branch',
3311
3187
                             help='Set identity for the current branch instead of '
3315
3191
    encoding_type = 'replace'
3316
3192
 
3317
3193
    @display_command
3318
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
3194
    def run(self, email=False, branch=False, name=None):
3319
3195
        if name is None:
3320
 
            if directory is None:
3321
 
                # use branch if we're inside one; otherwise global config
3322
 
                try:
3323
 
                    c = Branch.open_containing(u'.')[0].get_config()
3324
 
                except errors.NotBranchError:
3325
 
                    c = _mod_config.GlobalConfig()
3326
 
            else:
3327
 
                c = Branch.open(directory).get_config()
 
3196
            # use branch if we're inside one; otherwise global config
 
3197
            try:
 
3198
                c = Branch.open_containing('.')[0].get_config()
 
3199
            except errors.NotBranchError:
 
3200
                c = config.GlobalConfig()
3328
3201
            if email:
3329
3202
                self.outf.write(c.user_email() + '\n')
3330
3203
            else:
3333
3206
 
3334
3207
        # display a warning if an email address isn't included in the given name.
3335
3208
        try:
3336
 
            _mod_config.extract_email_address(name)
 
3209
            config.extract_email_address(name)
3337
3210
        except errors.NoEmailInUsername, e:
3338
3211
            warning('"%s" does not seem to contain an email address.  '
3339
3212
                    'This is allowed, but not recommended.', name)
3340
3213
 
3341
3214
        # use global config unless --branch given
3342
3215
        if branch:
3343
 
            if directory is None:
3344
 
                c = Branch.open_containing(u'.')[0].get_config()
3345
 
            else:
3346
 
                c = Branch.open(directory).get_config()
 
3216
            c = Branch.open_containing('.')[0].get_config()
3347
3217
        else:
3348
 
            c = _mod_config.GlobalConfig()
 
3218
            c = config.GlobalConfig()
3349
3219
        c.set_user_option('email', name)
3350
3220
 
3351
3221
 
3352
3222
class cmd_nick(Command):
3353
 
    __doc__ = """Print or set the branch nickname.
 
3223
    """Print or set the branch nickname.
3354
3224
 
3355
3225
    If unset, the tree root directory name is used as the nickname.
3356
3226
    To print the current nickname, execute with no argument.
3361
3231
 
3362
3232
    _see_also = ['info']
3363
3233
    takes_args = ['nickname?']
3364
 
    takes_options = ['directory']
3365
 
    def run(self, nickname=None, directory=u'.'):
3366
 
        branch = Branch.open_containing(directory)[0]
 
3234
    def run(self, nickname=None):
 
3235
        branch = Branch.open_containing(u'.')[0]
3367
3236
        if nickname is None:
3368
3237
            self.printme(branch)
3369
3238
        else:
3371
3240
 
3372
3241
    @display_command
3373
3242
    def printme(self, branch):
3374
 
        self.outf.write('%s\n' % branch.nick)
 
3243
        print branch.nick
3375
3244
 
3376
3245
 
3377
3246
class cmd_alias(Command):
3378
 
    __doc__ = """Set/unset and display aliases.
 
3247
    """Set/unset and display aliases.
3379
3248
 
3380
3249
    :Examples:
3381
3250
        Show the current aliases::
3418
3287
                'bzr alias --remove expects an alias to remove.')
3419
3288
        # If alias is not found, print something like:
3420
3289
        # unalias: foo: not found
3421
 
        c = _mod_config.GlobalConfig()
 
3290
        c = config.GlobalConfig()
3422
3291
        c.unset_alias(alias_name)
3423
3292
 
3424
3293
    @display_command
3425
3294
    def print_aliases(self):
3426
3295
        """Print out the defined aliases in a similar format to bash."""
3427
 
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3296
        aliases = config.GlobalConfig().get_aliases()
3428
3297
        for key, value in sorted(aliases.iteritems()):
3429
3298
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3430
3299
 
3440
3309
 
3441
3310
    def set_alias(self, alias_name, alias_command):
3442
3311
        """Save the alias in the global config."""
3443
 
        c = _mod_config.GlobalConfig()
 
3312
        c = config.GlobalConfig()
3444
3313
        c.set_alias(alias_name, alias_command)
3445
3314
 
3446
3315
 
3447
3316
class cmd_selftest(Command):
3448
 
    __doc__ = """Run internal test suite.
 
3317
    """Run internal test suite.
3449
3318
 
3450
3319
    If arguments are given, they are regular expressions that say which tests
3451
3320
    should run.  Tests matching any expression are run, and other tests are
3478
3347
    Tests that need working space on disk use a common temporary directory,
3479
3348
    typically inside $TMPDIR or /tmp.
3480
3349
 
3481
 
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3482
 
    into a pdb postmortem session.
3483
 
 
3484
3350
    :Examples:
3485
3351
        Run only tests relating to 'ignore'::
3486
3352
 
3495
3361
    def get_transport_type(typestring):
3496
3362
        """Parse and return a transport specifier."""
3497
3363
        if typestring == "sftp":
3498
 
            from bzrlib.tests import stub_sftp
3499
 
            return stub_sftp.SFTPAbsoluteServer
 
3364
            from bzrlib.transport.sftp import SFTPAbsoluteServer
 
3365
            return SFTPAbsoluteServer
3500
3366
        if typestring == "memory":
3501
 
            from bzrlib.tests import test_server
3502
 
            return memory.MemoryServer
 
3367
            from bzrlib.transport.memory import MemoryServer
 
3368
            return MemoryServer
3503
3369
        if typestring == "fakenfs":
3504
 
            from bzrlib.tests import test_server
3505
 
            return test_server.FakeNFSServer
 
3370
            from bzrlib.transport.fakenfs import FakeNFSServer
 
3371
            return FakeNFSServer
3506
3372
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3507
3373
            (typestring)
3508
3374
        raise errors.BzrCommandError(msg)
3519
3385
                                 'throughout the test suite.',
3520
3386
                            type=get_transport_type),
3521
3387
                     Option('benchmark',
3522
 
                            help='Run the benchmarks rather than selftests.',
3523
 
                            hidden=True),
 
3388
                            help='Run the benchmarks rather than selftests.'),
3524
3389
                     Option('lsprof-timed',
3525
3390
                            help='Generate lsprof output for benchmarked'
3526
3391
                                 ' sections of code.'),
3527
 
                     Option('lsprof-tests',
3528
 
                            help='Generate lsprof output for each test.'),
 
3392
                     Option('cache-dir', type=str,
 
3393
                            help='Cache intermediate benchmark output in this '
 
3394
                                 'directory.'),
3529
3395
                     Option('first',
3530
3396
                            help='Run all tests, but run specified tests first.',
3531
3397
                            short_name='f',
3565
3431
 
3566
3432
    def run(self, testspecs_list=None, verbose=False, one=False,
3567
3433
            transport=None, benchmark=None,
3568
 
            lsprof_timed=None,
 
3434
            lsprof_timed=None, cache_dir=None,
3569
3435
            first=False, list_only=False,
3570
3436
            randomize=None, exclude=None, strict=False,
3571
3437
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3572
 
            parallel=None, lsprof_tests=False):
3573
 
        from bzrlib import tests
3574
 
 
 
3438
            parallel=None):
 
3439
        from bzrlib.tests import selftest
 
3440
        import bzrlib.benchmarks as benchmarks
 
3441
        from bzrlib.benchmarks import tree_creator
 
3442
 
 
3443
        # Make deprecation warnings visible, unless -Werror is set
 
3444
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3445
 
 
3446
        if cache_dir is not None:
 
3447
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3575
3448
        if testspecs_list is not None:
3576
3449
            pattern = '|'.join(testspecs_list)
3577
3450
        else:
3583
3456
                raise errors.BzrCommandError("subunit not available. subunit "
3584
3457
                    "needs to be installed to use --subunit.")
3585
3458
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3586
 
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3587
 
            # stdout, which would corrupt the subunit stream. 
3588
 
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3589
 
            # following code can be deleted when it's sufficiently deployed
3590
 
            # -- vila/mgz 20100514
3591
 
            if (sys.platform == "win32"
3592
 
                and getattr(sys.stdout, 'fileno', None) is not None):
3593
 
                import msvcrt
3594
 
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3595
3459
        if parallel:
3596
3460
            self.additional_selftest_args.setdefault(
3597
3461
                'suite_decorators', []).append(parallel)
3598
3462
        if benchmark:
3599
 
            raise errors.BzrCommandError(
3600
 
                "--benchmark is no longer supported from bzr 2.2; "
3601
 
                "use bzr-usertest instead")
3602
 
        test_suite_factory = None
3603
 
        selftest_kwargs = {"verbose": verbose,
3604
 
                          "pattern": pattern,
3605
 
                          "stop_on_failure": one,
3606
 
                          "transport": transport,
3607
 
                          "test_suite_factory": test_suite_factory,
3608
 
                          "lsprof_timed": lsprof_timed,
3609
 
                          "lsprof_tests": lsprof_tests,
3610
 
                          "matching_tests_first": first,
3611
 
                          "list_only": list_only,
3612
 
                          "random_seed": randomize,
3613
 
                          "exclude_pattern": exclude,
3614
 
                          "strict": strict,
3615
 
                          "load_list": load_list,
3616
 
                          "debug_flags": debugflag,
3617
 
                          "starting_with": starting_with
3618
 
                          }
3619
 
        selftest_kwargs.update(self.additional_selftest_args)
3620
 
 
3621
 
        # Make deprecation warnings visible, unless -Werror is set
3622
 
        cleanup = symbol_versioning.activate_deprecation_warnings(
3623
 
            override=False)
 
3463
            test_suite_factory = benchmarks.test_suite
 
3464
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3465
            verbose = not is_quiet()
 
3466
            # TODO: should possibly lock the history file...
 
3467
            benchfile = open(".perf_history", "at", buffering=1)
 
3468
        else:
 
3469
            test_suite_factory = None
 
3470
            benchfile = None
3624
3471
        try:
3625
 
            result = tests.selftest(**selftest_kwargs)
 
3472
            selftest_kwargs = {"verbose": verbose,
 
3473
                              "pattern": pattern,
 
3474
                              "stop_on_failure": one,
 
3475
                              "transport": transport,
 
3476
                              "test_suite_factory": test_suite_factory,
 
3477
                              "lsprof_timed": lsprof_timed,
 
3478
                              "bench_history": benchfile,
 
3479
                              "matching_tests_first": first,
 
3480
                              "list_only": list_only,
 
3481
                              "random_seed": randomize,
 
3482
                              "exclude_pattern": exclude,
 
3483
                              "strict": strict,
 
3484
                              "load_list": load_list,
 
3485
                              "debug_flags": debugflag,
 
3486
                              "starting_with": starting_with
 
3487
                              }
 
3488
            selftest_kwargs.update(self.additional_selftest_args)
 
3489
            result = selftest(**selftest_kwargs)
3626
3490
        finally:
3627
 
            cleanup()
 
3491
            if benchfile is not None:
 
3492
                benchfile.close()
3628
3493
        return int(not result)
3629
3494
 
3630
3495
 
3631
3496
class cmd_version(Command):
3632
 
    __doc__ = """Show version of bzr."""
 
3497
    """Show version of bzr."""
3633
3498
 
3634
3499
    encoding_type = 'replace'
3635
3500
    takes_options = [
3646
3511
 
3647
3512
 
3648
3513
class cmd_rocks(Command):
3649
 
    __doc__ = """Statement of optimism."""
 
3514
    """Statement of optimism."""
3650
3515
 
3651
3516
    hidden = True
3652
3517
 
3653
3518
    @display_command
3654
3519
    def run(self):
3655
 
        self.outf.write("It sure does!\n")
 
3520
        print "It sure does!"
3656
3521
 
3657
3522
 
3658
3523
class cmd_find_merge_base(Command):
3659
 
    __doc__ = """Find and print a base revision for merging two branches."""
 
3524
    """Find and print a base revision for merging two branches."""
3660
3525
    # TODO: Options to specify revisions on either side, as if
3661
3526
    #       merging only part of the history.
3662
3527
    takes_args = ['branch', 'other']
3668
3533
 
3669
3534
        branch1 = Branch.open_containing(branch)[0]
3670
3535
        branch2 = Branch.open_containing(other)[0]
3671
 
        self.add_cleanup(branch1.lock_read().unlock)
3672
 
        self.add_cleanup(branch2.lock_read().unlock)
3673
 
        last1 = ensure_null(branch1.last_revision())
3674
 
        last2 = ensure_null(branch2.last_revision())
3675
 
 
3676
 
        graph = branch1.repository.get_graph(branch2.repository)
3677
 
        base_rev_id = graph.find_unique_lca(last1, last2)
3678
 
 
3679
 
        self.outf.write('merge base is revision %s\n' % base_rev_id)
 
3536
        branch1.lock_read()
 
3537
        try:
 
3538
            branch2.lock_read()
 
3539
            try:
 
3540
                last1 = ensure_null(branch1.last_revision())
 
3541
                last2 = ensure_null(branch2.last_revision())
 
3542
 
 
3543
                graph = branch1.repository.get_graph(branch2.repository)
 
3544
                base_rev_id = graph.find_unique_lca(last1, last2)
 
3545
 
 
3546
                print 'merge base is revision %s' % base_rev_id
 
3547
            finally:
 
3548
                branch2.unlock()
 
3549
        finally:
 
3550
            branch1.unlock()
3680
3551
 
3681
3552
 
3682
3553
class cmd_merge(Command):
3683
 
    __doc__ = """Perform a three-way merge.
 
3554
    """Perform a three-way merge.
3684
3555
 
3685
3556
    The source of the merge can be specified either in the form of a branch,
3686
3557
    or in the form of a path to a file containing a merge directive generated
3715
3586
    committed to record the result of the merge.
3716
3587
 
3717
3588
    merge refuses to run if there are any uncommitted changes, unless
3718
 
    --force is given. The --force option can also be used to create a
3719
 
    merge revision which has more than two parents.
3720
 
 
3721
 
    If one would like to merge changes from the working tree of the other
3722
 
    branch without merging any committed revisions, the --uncommitted option
3723
 
    can be given.
 
3589
    --force is given.
3724
3590
 
3725
3591
    To select only some changes to merge, use "merge -i", which will prompt
3726
3592
    you to apply each diff hunk and file change, similar to "shelve".
3738
3604
 
3739
3605
            bzr merge -r 81..82 ../bzr.dev
3740
3606
 
3741
 
        To apply a merge directive contained in /tmp/merge::
 
3607
        To apply a merge directive contained in /tmp/merge:
3742
3608
 
3743
3609
            bzr merge /tmp/merge
3744
 
 
3745
 
        To create a merge revision with three parents from two branches
3746
 
        feature1a and feature1b:
3747
 
 
3748
 
            bzr merge ../feature1a
3749
 
            bzr merge ../feature1b --force
3750
 
            bzr commit -m 'revision with three parents'
3751
3610
    """
3752
3611
 
3753
3612
    encoding_type = 'exact'
3769
3628
                ' completely merged into the source, pull from the'
3770
3629
                ' source rather than merging.  When this happens,'
3771
3630
                ' you do not need to commit the result.'),
3772
 
        custom_help('directory',
 
3631
        Option('directory',
3773
3632
               help='Branch to merge into, '
3774
 
                    'rather than the one containing the working directory.'),
 
3633
                    'rather than the one containing the working directory.',
 
3634
               short_name='d',
 
3635
               type=unicode,
 
3636
               ),
3775
3637
        Option('preview', help='Instead of merging, show a diff of the'
3776
3638
               ' merge.'),
3777
3639
        Option('interactive', help='Select changes interactively.',
3795
3657
        verified = 'inapplicable'
3796
3658
        tree = WorkingTree.open_containing(directory)[0]
3797
3659
 
 
3660
        # die as quickly as possible if there are uncommitted changes
3798
3661
        try:
3799
3662
            basis_tree = tree.revision_tree(tree.last_revision())
3800
3663
        except errors.NoSuchRevision:
3801
3664
            basis_tree = tree.basis_tree()
3802
 
 
3803
 
        # die as quickly as possible if there are uncommitted changes
3804
3665
        if not force:
3805
 
            if tree.has_changes():
 
3666
            if tree.has_changes(basis_tree):
3806
3667
                raise errors.UncommittedChanges(tree)
3807
3668
 
3808
3669
        view_info = _get_view_info_for_change_reporter(tree)
3809
3670
        change_reporter = delta._ChangeReporter(
3810
3671
            unversioned_filter=tree.is_ignored, view_info=view_info)
3811
 
        pb = ui.ui_factory.nested_progress_bar()
3812
 
        self.add_cleanup(pb.finished)
3813
 
        self.add_cleanup(tree.lock_write().unlock)
3814
 
        if location is not None:
3815
 
            try:
3816
 
                mergeable = bundle.read_mergeable_from_url(location,
3817
 
                    possible_transports=possible_transports)
3818
 
            except errors.NotABundle:
3819
 
                mergeable = None
 
3672
        cleanups = []
 
3673
        try:
 
3674
            pb = ui.ui_factory.nested_progress_bar()
 
3675
            cleanups.append(pb.finished)
 
3676
            tree.lock_write()
 
3677
            cleanups.append(tree.unlock)
 
3678
            if location is not None:
 
3679
                try:
 
3680
                    mergeable = bundle.read_mergeable_from_url(location,
 
3681
                        possible_transports=possible_transports)
 
3682
                except errors.NotABundle:
 
3683
                    mergeable = None
 
3684
                else:
 
3685
                    if uncommitted:
 
3686
                        raise errors.BzrCommandError('Cannot use --uncommitted'
 
3687
                            ' with bundles or merge directives.')
 
3688
 
 
3689
                    if revision is not None:
 
3690
                        raise errors.BzrCommandError(
 
3691
                            'Cannot use -r with merge directives or bundles')
 
3692
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
3693
                       mergeable, pb)
 
3694
 
 
3695
            if merger is None and uncommitted:
 
3696
                if revision is not None and len(revision) > 0:
 
3697
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
 
3698
                        ' --revision at the same time.')
 
3699
                merger = self.get_merger_from_uncommitted(tree, location, pb,
 
3700
                                                          cleanups)
 
3701
                allow_pending = False
 
3702
 
 
3703
            if merger is None:
 
3704
                merger, allow_pending = self._get_merger_from_branch(tree,
 
3705
                    location, revision, remember, possible_transports, pb)
 
3706
 
 
3707
            merger.merge_type = merge_type
 
3708
            merger.reprocess = reprocess
 
3709
            merger.show_base = show_base
 
3710
            self.sanity_check_merger(merger)
 
3711
            if (merger.base_rev_id == merger.other_rev_id and
 
3712
                merger.other_rev_id is not None):
 
3713
                note('Nothing to do.')
 
3714
                return 0
 
3715
            if pull:
 
3716
                if merger.interesting_files is not None:
 
3717
                    raise errors.BzrCommandError('Cannot pull individual files')
 
3718
                if (merger.base_rev_id == tree.last_revision()):
 
3719
                    result = tree.pull(merger.other_branch, False,
 
3720
                                       merger.other_rev_id)
 
3721
                    result.report(self.outf)
 
3722
                    return 0
 
3723
            merger.check_basis(False)
 
3724
            if preview:
 
3725
                return self._do_preview(merger, cleanups)
 
3726
            elif interactive:
 
3727
                return self._do_interactive(merger, cleanups)
3820
3728
            else:
3821
 
                if uncommitted:
3822
 
                    raise errors.BzrCommandError('Cannot use --uncommitted'
3823
 
                        ' with bundles or merge directives.')
3824
 
 
3825
 
                if revision is not None:
3826
 
                    raise errors.BzrCommandError(
3827
 
                        'Cannot use -r with merge directives or bundles')
3828
 
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
3829
 
                   mergeable, None)
3830
 
 
3831
 
        if merger is None and uncommitted:
3832
 
            if revision is not None and len(revision) > 0:
3833
 
                raise errors.BzrCommandError('Cannot use --uncommitted and'
3834
 
                    ' --revision at the same time.')
3835
 
            merger = self.get_merger_from_uncommitted(tree, location, None)
3836
 
            allow_pending = False
3837
 
 
3838
 
        if merger is None:
3839
 
            merger, allow_pending = self._get_merger_from_branch(tree,
3840
 
                location, revision, remember, possible_transports, None)
3841
 
 
3842
 
        merger.merge_type = merge_type
3843
 
        merger.reprocess = reprocess
3844
 
        merger.show_base = show_base
3845
 
        self.sanity_check_merger(merger)
3846
 
        if (merger.base_rev_id == merger.other_rev_id and
3847
 
            merger.other_rev_id is not None):
3848
 
            note('Nothing to do.')
3849
 
            return 0
3850
 
        if pull:
3851
 
            if merger.interesting_files is not None:
3852
 
                raise errors.BzrCommandError('Cannot pull individual files')
3853
 
            if (merger.base_rev_id == tree.last_revision()):
3854
 
                result = tree.pull(merger.other_branch, False,
3855
 
                                   merger.other_rev_id)
3856
 
                result.report(self.outf)
3857
 
                return 0
3858
 
        if merger.this_basis is None:
3859
 
            raise errors.BzrCommandError(
3860
 
                "This branch has no commits."
3861
 
                " (perhaps you would prefer 'bzr pull')")
3862
 
        if preview:
3863
 
            return self._do_preview(merger)
3864
 
        elif interactive:
3865
 
            return self._do_interactive(merger)
3866
 
        else:
3867
 
            return self._do_merge(merger, change_reporter, allow_pending,
3868
 
                                  verified)
3869
 
 
3870
 
    def _get_preview(self, merger):
 
3729
                return self._do_merge(merger, change_reporter, allow_pending,
 
3730
                                      verified)
 
3731
        finally:
 
3732
            for cleanup in reversed(cleanups):
 
3733
                cleanup()
 
3734
 
 
3735
    def _get_preview(self, merger, cleanups):
3871
3736
        tree_merger = merger.make_merger()
3872
3737
        tt = tree_merger.make_preview_transform()
3873
 
        self.add_cleanup(tt.finalize)
 
3738
        cleanups.append(tt.finalize)
3874
3739
        result_tree = tt.get_preview_tree()
3875
3740
        return result_tree
3876
3741
 
3877
 
    def _do_preview(self, merger):
 
3742
    def _do_preview(self, merger, cleanups):
3878
3743
        from bzrlib.diff import show_diff_trees
3879
 
        result_tree = self._get_preview(merger)
3880
 
        path_encoding = osutils.get_diff_header_encoding()
 
3744
        result_tree = self._get_preview(merger, cleanups)
3881
3745
        show_diff_trees(merger.this_tree, result_tree, self.outf,
3882
 
                        old_label='', new_label='',
3883
 
                        path_encoding=path_encoding)
 
3746
                        old_label='', new_label='')
3884
3747
 
3885
3748
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3886
3749
        merger.change_reporter = change_reporter
3894
3757
        else:
3895
3758
            return 0
3896
3759
 
3897
 
    def _do_interactive(self, merger):
 
3760
    def _do_interactive(self, merger, cleanups):
3898
3761
        """Perform an interactive merge.
3899
3762
 
3900
3763
        This works by generating a preview tree of the merge, then using
3902
3765
        and the preview tree.
3903
3766
        """
3904
3767
        from bzrlib import shelf_ui
3905
 
        result_tree = self._get_preview(merger)
 
3768
        result_tree = self._get_preview(merger, cleanups)
3906
3769
        writer = bzrlib.option.diff_writer_registry.get()
3907
3770
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
3908
3771
                                   reporter=shelf_ui.ApplyReporter(),
3909
3772
                                   diff_writer=writer(sys.stdout))
3910
 
        try:
3911
 
            shelver.run()
3912
 
        finally:
3913
 
            shelver.finalize()
 
3773
        shelver.run()
3914
3774
 
3915
3775
    def sanity_check_merger(self, merger):
3916
3776
        if (merger.show_base and
3976
3836
            allow_pending = True
3977
3837
        return merger, allow_pending
3978
3838
 
3979
 
    def get_merger_from_uncommitted(self, tree, location, pb):
 
3839
    def get_merger_from_uncommitted(self, tree, location, pb, cleanups):
3980
3840
        """Get a merger for uncommitted changes.
3981
3841
 
3982
3842
        :param tree: The tree the merger should apply to.
3983
3843
        :param location: The location containing uncommitted changes.
3984
3844
        :param pb: The progress bar to use for showing progress.
 
3845
        :param cleanups: A list of operations to perform to clean up the
 
3846
            temporary directories, unfinalized objects, etc.
3985
3847
        """
3986
3848
        location = self._select_branch_location(tree, location)[0]
3987
3849
        other_tree, other_path = WorkingTree.open_containing(location)
4039
3901
 
4040
3902
 
4041
3903
class cmd_remerge(Command):
4042
 
    __doc__ = """Redo a merge.
 
3904
    """Redo a merge.
4043
3905
 
4044
3906
    Use this if you want to try a different merge technique while resolving
4045
3907
    conflicts.  Some merge techniques are better than others, and remerge
4070
3932
 
4071
3933
    def run(self, file_list=None, merge_type=None, show_base=False,
4072
3934
            reprocess=False):
4073
 
        from bzrlib.conflicts import restore
4074
3935
        if merge_type is None:
4075
3936
            merge_type = _mod_merge.Merge3Merger
4076
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4077
 
        self.add_cleanup(tree.lock_write().unlock)
4078
 
        parents = tree.get_parent_ids()
4079
 
        if len(parents) != 2:
4080
 
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4081
 
                                         " merges.  Not cherrypicking or"
4082
 
                                         " multi-merges.")
4083
 
        repository = tree.branch.repository
4084
 
        interesting_ids = None
4085
 
        new_conflicts = []
4086
 
        conflicts = tree.conflicts()
4087
 
        if file_list is not None:
4088
 
            interesting_ids = set()
4089
 
            for filename in file_list:
4090
 
                file_id = tree.path2id(filename)
4091
 
                if file_id is None:
4092
 
                    raise errors.NotVersionedError(filename)
4093
 
                interesting_ids.add(file_id)
4094
 
                if tree.kind(file_id) != "directory":
4095
 
                    continue
 
3937
        tree, file_list = tree_files(file_list)
 
3938
        tree.lock_write()
 
3939
        try:
 
3940
            parents = tree.get_parent_ids()
 
3941
            if len(parents) != 2:
 
3942
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
 
3943
                                             " merges.  Not cherrypicking or"
 
3944
                                             " multi-merges.")
 
3945
            repository = tree.branch.repository
 
3946
            interesting_ids = None
 
3947
            new_conflicts = []
 
3948
            conflicts = tree.conflicts()
 
3949
            if file_list is not None:
 
3950
                interesting_ids = set()
 
3951
                for filename in file_list:
 
3952
                    file_id = tree.path2id(filename)
 
3953
                    if file_id is None:
 
3954
                        raise errors.NotVersionedError(filename)
 
3955
                    interesting_ids.add(file_id)
 
3956
                    if tree.kind(file_id) != "directory":
 
3957
                        continue
4096
3958
 
4097
 
                for name, ie in tree.inventory.iter_entries(file_id):
4098
 
                    interesting_ids.add(ie.file_id)
4099
 
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4100
 
        else:
4101
 
            # Remerge only supports resolving contents conflicts
4102
 
            allowed_conflicts = ('text conflict', 'contents conflict')
4103
 
            restore_files = [c.path for c in conflicts
4104
 
                             if c.typestring in allowed_conflicts]
4105
 
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4106
 
        tree.set_conflicts(ConflictList(new_conflicts))
4107
 
        if file_list is not None:
4108
 
            restore_files = file_list
4109
 
        for filename in restore_files:
 
3959
                    for name, ie in tree.inventory.iter_entries(file_id):
 
3960
                        interesting_ids.add(ie.file_id)
 
3961
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
3962
            else:
 
3963
                # Remerge only supports resolving contents conflicts
 
3964
                allowed_conflicts = ('text conflict', 'contents conflict')
 
3965
                restore_files = [c.path for c in conflicts
 
3966
                                 if c.typestring in allowed_conflicts]
 
3967
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
 
3968
            tree.set_conflicts(ConflictList(new_conflicts))
 
3969
            if file_list is not None:
 
3970
                restore_files = file_list
 
3971
            for filename in restore_files:
 
3972
                try:
 
3973
                    restore(tree.abspath(filename))
 
3974
                except errors.NotConflicted:
 
3975
                    pass
 
3976
            # Disable pending merges, because the file texts we are remerging
 
3977
            # have not had those merges performed.  If we use the wrong parents
 
3978
            # list, we imply that the working tree text has seen and rejected
 
3979
            # all the changes from the other tree, when in fact those changes
 
3980
            # have not yet been seen.
 
3981
            pb = ui.ui_factory.nested_progress_bar()
 
3982
            tree.set_parent_ids(parents[:1])
4110
3983
            try:
4111
 
                restore(tree.abspath(filename))
4112
 
            except errors.NotConflicted:
4113
 
                pass
4114
 
        # Disable pending merges, because the file texts we are remerging
4115
 
        # have not had those merges performed.  If we use the wrong parents
4116
 
        # list, we imply that the working tree text has seen and rejected
4117
 
        # all the changes from the other tree, when in fact those changes
4118
 
        # have not yet been seen.
4119
 
        tree.set_parent_ids(parents[:1])
4120
 
        try:
4121
 
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4122
 
            merger.interesting_ids = interesting_ids
4123
 
            merger.merge_type = merge_type
4124
 
            merger.show_base = show_base
4125
 
            merger.reprocess = reprocess
4126
 
            conflicts = merger.do_merge()
 
3984
                merger = _mod_merge.Merger.from_revision_ids(pb,
 
3985
                                                             tree, parents[1])
 
3986
                merger.interesting_ids = interesting_ids
 
3987
                merger.merge_type = merge_type
 
3988
                merger.show_base = show_base
 
3989
                merger.reprocess = reprocess
 
3990
                conflicts = merger.do_merge()
 
3991
            finally:
 
3992
                tree.set_parent_ids(parents)
 
3993
                pb.finished()
4127
3994
        finally:
4128
 
            tree.set_parent_ids(parents)
 
3995
            tree.unlock()
4129
3996
        if conflicts > 0:
4130
3997
            return 1
4131
3998
        else:
4133
4000
 
4134
4001
 
4135
4002
class cmd_revert(Command):
4136
 
    __doc__ = """Revert files to a previous revision.
 
4003
    """Revert files to a previous revision.
4137
4004
 
4138
4005
    Giving a list of files will revert only those files.  Otherwise, all files
4139
4006
    will be reverted.  If the revision is not specified with '--revision', the
4153
4020
    name.  If you name a directory, all the contents of that directory will be
4154
4021
    reverted.
4155
4022
 
4156
 
    If you have newly added files since the target revision, they will be
4157
 
    removed.  If the files to be removed have been changed, backups will be
4158
 
    created as above.  Directories containing unknown files will not be
4159
 
    deleted.
 
4023
    Any files that have been newly added since that revision will be deleted,
 
4024
    with a backup kept if appropriate.  Directories containing unknown files
 
4025
    will not be deleted.
4160
4026
 
4161
 
    The working tree contains a list of revisions that have been merged but
4162
 
    not yet committed. These revisions will be included as additional parents
4163
 
    of the next commit.  Normally, using revert clears that list as well as
4164
 
    reverting the files.  If any files are specified, revert leaves the list
4165
 
    of uncommitted merges alone and reverts only the files.  Use ``bzr revert
4166
 
    .`` in the tree root to revert all files but keep the recorded merges,
4167
 
    and ``bzr revert --forget-merges`` to clear the pending merge list without
 
4027
    The working tree contains a list of pending merged revisions, which will
 
4028
    be included as parents in the next commit.  Normally, revert clears that
 
4029
    list as well as reverting the files.  If any files are specified, revert
 
4030
    leaves the pending merge list alone and reverts only the files.  Use "bzr
 
4031
    revert ." in the tree root to revert all files but keep the merge record,
 
4032
    and "bzr revert --forget-merges" to clear the pending merge list without
4168
4033
    reverting any files.
4169
 
 
4170
 
    Using "bzr revert --forget-merges", it is possible to apply all of the
4171
 
    changes from a branch in a single revision.  To do this, perform the merge
4172
 
    as desired.  Then doing revert with the "--forget-merges" option will keep
4173
 
    the content of the tree as it was, but it will clear the list of pending
4174
 
    merges.  The next commit will then contain all of the changes that are
4175
 
    present in the other branch, but without any other parent revisions.
4176
 
    Because this technique forgets where these changes originated, it may
4177
 
    cause additional conflicts on later merges involving the same source and
4178
 
    target branches.
4179
4034
    """
4180
4035
 
4181
4036
    _see_also = ['cat', 'export']
4189
4044
 
4190
4045
    def run(self, revision=None, no_backup=False, file_list=None,
4191
4046
            forget_merges=None):
4192
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4193
 
        self.add_cleanup(tree.lock_tree_write().unlock)
4194
 
        if forget_merges:
4195
 
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4196
 
        else:
4197
 
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4047
        tree, file_list = tree_files(file_list)
 
4048
        tree.lock_tree_write()
 
4049
        try:
 
4050
            if forget_merges:
 
4051
                tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4052
            else:
 
4053
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4054
        finally:
 
4055
            tree.unlock()
4198
4056
 
4199
4057
    @staticmethod
4200
4058
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
4201
4059
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4202
 
        tree.revert(file_list, rev_tree, not no_backup, None,
4203
 
            report_changes=True)
 
4060
        pb = ui.ui_factory.nested_progress_bar()
 
4061
        try:
 
4062
            tree.revert(file_list, rev_tree, not no_backup, pb,
 
4063
                report_changes=True)
 
4064
        finally:
 
4065
            pb.finished()
4204
4066
 
4205
4067
 
4206
4068
class cmd_assert_fail(Command):
4207
 
    __doc__ = """Test reporting of assertion failures"""
 
4069
    """Test reporting of assertion failures"""
4208
4070
    # intended just for use in testing
4209
4071
 
4210
4072
    hidden = True
4214
4076
 
4215
4077
 
4216
4078
class cmd_help(Command):
4217
 
    __doc__ = """Show help on a command or other topic.
 
4079
    """Show help on a command or other topic.
4218
4080
    """
4219
4081
 
4220
4082
    _see_also = ['topics']
4233
4095
 
4234
4096
 
4235
4097
class cmd_shell_complete(Command):
4236
 
    __doc__ = """Show appropriate completions for context.
 
4098
    """Show appropriate completions for context.
4237
4099
 
4238
4100
    For a list of all available commands, say 'bzr shell-complete'.
4239
4101
    """
4248
4110
 
4249
4111
 
4250
4112
class cmd_missing(Command):
4251
 
    __doc__ = """Show unmerged/unpulled revisions between two branches.
 
4113
    """Show unmerged/unpulled revisions between two branches.
4252
4114
 
4253
4115
    OTHER_BRANCH may be local or remote.
4254
4116
 
4255
4117
    To filter on a range of revisions, you can use the command -r begin..end
4256
4118
    -r revision requests a specific revision, -r ..end or -r begin.. are
4257
4119
    also valid.
4258
 
            
4259
 
    :Exit values:
4260
 
        1 - some missing revisions
4261
 
        0 - no missing revisions
4262
4120
 
4263
4121
    :Examples:
4264
4122
 
4285
4143
    _see_also = ['merge', 'pull']
4286
4144
    takes_args = ['other_branch?']
4287
4145
    takes_options = [
4288
 
        'directory',
4289
4146
        Option('reverse', 'Reverse the order of revisions.'),
4290
4147
        Option('mine-only',
4291
4148
               'Display changes in the local branch only.'),
4313
4170
            theirs_only=False,
4314
4171
            log_format=None, long=False, short=False, line=False,
4315
4172
            show_ids=False, verbose=False, this=False, other=False,
4316
 
            include_merges=False, revision=None, my_revision=None,
4317
 
            directory=u'.'):
 
4173
            include_merges=False, revision=None, my_revision=None):
4318
4174
        from bzrlib.missing import find_unmerged, iter_log_revisions
4319
4175
        def message(s):
4320
4176
            if not is_quiet():
4333
4189
        elif theirs_only:
4334
4190
            restrict = 'remote'
4335
4191
 
4336
 
        local_branch = Branch.open_containing(directory)[0]
4337
 
        self.add_cleanup(local_branch.lock_read().unlock)
4338
 
 
 
4192
        local_branch = Branch.open_containing(u".")[0]
4339
4193
        parent = local_branch.get_parent()
4340
4194
        if other_branch is None:
4341
4195
            other_branch = parent
4350
4204
        remote_branch = Branch.open(other_branch)
4351
4205
        if remote_branch.base == local_branch.base:
4352
4206
            remote_branch = local_branch
4353
 
        else:
4354
 
            self.add_cleanup(remote_branch.lock_read().unlock)
4355
4207
 
4356
4208
        local_revid_range = _revision_range_to_revid_range(
4357
4209
            _get_revision_range(my_revision, local_branch,
4361
4213
            _get_revision_range(revision,
4362
4214
                remote_branch, self.name()))
4363
4215
 
4364
 
        local_extra, remote_extra = find_unmerged(
4365
 
            local_branch, remote_branch, restrict,
4366
 
            backward=not reverse,
4367
 
            include_merges=include_merges,
4368
 
            local_revid_range=local_revid_range,
4369
 
            remote_revid_range=remote_revid_range)
4370
 
 
4371
 
        if log_format is None:
4372
 
            registry = log.log_formatter_registry
4373
 
            log_format = registry.get_default(local_branch)
4374
 
        lf = log_format(to_file=self.outf,
4375
 
                        show_ids=show_ids,
4376
 
                        show_timezone='original')
4377
 
 
4378
 
        status_code = 0
4379
 
        if local_extra and not theirs_only:
4380
 
            message("You have %d extra revision(s):\n" %
4381
 
                len(local_extra))
4382
 
            for revision in iter_log_revisions(local_extra,
4383
 
                                local_branch.repository,
4384
 
                                verbose):
4385
 
                lf.log_revision(revision)
4386
 
            printed_local = True
4387
 
            status_code = 1
4388
 
        else:
4389
 
            printed_local = False
4390
 
 
4391
 
        if remote_extra and not mine_only:
4392
 
            if printed_local is True:
4393
 
                message("\n\n\n")
4394
 
            message("You are missing %d revision(s):\n" %
4395
 
                len(remote_extra))
4396
 
            for revision in iter_log_revisions(remote_extra,
4397
 
                                remote_branch.repository,
4398
 
                                verbose):
4399
 
                lf.log_revision(revision)
4400
 
            status_code = 1
4401
 
 
4402
 
        if mine_only and not local_extra:
4403
 
            # We checked local, and found nothing extra
4404
 
            message('This branch is up to date.\n')
4405
 
        elif theirs_only and not remote_extra:
4406
 
            # We checked remote, and found nothing extra
4407
 
            message('Other branch is up to date.\n')
4408
 
        elif not (mine_only or theirs_only or local_extra or
4409
 
                  remote_extra):
4410
 
            # We checked both branches, and neither one had extra
4411
 
            # revisions
4412
 
            message("Branches are up to date.\n")
4413
 
        self.cleanup_now()
 
4216
        local_branch.lock_read()
 
4217
        try:
 
4218
            remote_branch.lock_read()
 
4219
            try:
 
4220
                local_extra, remote_extra = find_unmerged(
 
4221
                    local_branch, remote_branch, restrict,
 
4222
                    backward=not reverse,
 
4223
                    include_merges=include_merges,
 
4224
                    local_revid_range=local_revid_range,
 
4225
                    remote_revid_range=remote_revid_range)
 
4226
 
 
4227
                if log_format is None:
 
4228
                    registry = log.log_formatter_registry
 
4229
                    log_format = registry.get_default(local_branch)
 
4230
                lf = log_format(to_file=self.outf,
 
4231
                                show_ids=show_ids,
 
4232
                                show_timezone='original')
 
4233
 
 
4234
                status_code = 0
 
4235
                if local_extra and not theirs_only:
 
4236
                    message("You have %d extra revision(s):\n" %
 
4237
                        len(local_extra))
 
4238
                    for revision in iter_log_revisions(local_extra,
 
4239
                                        local_branch.repository,
 
4240
                                        verbose):
 
4241
                        lf.log_revision(revision)
 
4242
                    printed_local = True
 
4243
                    status_code = 1
 
4244
                else:
 
4245
                    printed_local = False
 
4246
 
 
4247
                if remote_extra and not mine_only:
 
4248
                    if printed_local is True:
 
4249
                        message("\n\n\n")
 
4250
                    message("You are missing %d revision(s):\n" %
 
4251
                        len(remote_extra))
 
4252
                    for revision in iter_log_revisions(remote_extra,
 
4253
                                        remote_branch.repository,
 
4254
                                        verbose):
 
4255
                        lf.log_revision(revision)
 
4256
                    status_code = 1
 
4257
 
 
4258
                if mine_only and not local_extra:
 
4259
                    # We checked local, and found nothing extra
 
4260
                    message('This branch is up to date.\n')
 
4261
                elif theirs_only and not remote_extra:
 
4262
                    # We checked remote, and found nothing extra
 
4263
                    message('Other branch is up to date.\n')
 
4264
                elif not (mine_only or theirs_only or local_extra or
 
4265
                          remote_extra):
 
4266
                    # We checked both branches, and neither one had extra
 
4267
                    # revisions
 
4268
                    message("Branches are up to date.\n")
 
4269
            finally:
 
4270
                remote_branch.unlock()
 
4271
        finally:
 
4272
            local_branch.unlock()
4414
4273
        if not status_code and parent is None and other_branch is not None:
4415
 
            self.add_cleanup(local_branch.lock_write().unlock)
4416
 
            # handle race conditions - a parent might be set while we run.
4417
 
            if local_branch.get_parent() is None:
4418
 
                local_branch.set_parent(remote_branch.base)
 
4274
            local_branch.lock_write()
 
4275
            try:
 
4276
                # handle race conditions - a parent might be set while we run.
 
4277
                if local_branch.get_parent() is None:
 
4278
                    local_branch.set_parent(remote_branch.base)
 
4279
            finally:
 
4280
                local_branch.unlock()
4419
4281
        return status_code
4420
4282
 
4421
4283
 
4422
4284
class cmd_pack(Command):
4423
 
    __doc__ = """Compress the data within a repository.
4424
 
 
4425
 
    This operation compresses the data within a bazaar repository. As
4426
 
    bazaar supports automatic packing of repository, this operation is
4427
 
    normally not required to be done manually.
4428
 
 
4429
 
    During the pack operation, bazaar takes a backup of existing repository
4430
 
    data, i.e. pack files. This backup is eventually removed by bazaar
4431
 
    automatically when it is safe to do so. To save disk space by removing
4432
 
    the backed up pack files, the --clean-obsolete-packs option may be
4433
 
    used.
4434
 
 
4435
 
    Warning: If you use --clean-obsolete-packs and your machine crashes
4436
 
    during or immediately after repacking, you may be left with a state
4437
 
    where the deletion has been written to disk but the new packs have not
4438
 
    been. In this case the repository may be unusable.
4439
 
    """
 
4285
    """Compress the data within a repository."""
4440
4286
 
4441
4287
    _see_also = ['repositories']
4442
4288
    takes_args = ['branch_or_repo?']
4443
 
    takes_options = [
4444
 
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4445
 
        ]
4446
4289
 
4447
 
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
 
4290
    def run(self, branch_or_repo='.'):
4448
4291
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4449
4292
        try:
4450
4293
            branch = dir.open_branch()
4451
4294
            repository = branch.repository
4452
4295
        except errors.NotBranchError:
4453
4296
            repository = dir.open_repository()
4454
 
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
4297
        repository.pack()
4455
4298
 
4456
4299
 
4457
4300
class cmd_plugins(Command):
4458
 
    __doc__ = """List the installed plugins.
 
4301
    """List the installed plugins.
4459
4302
 
4460
4303
    This command displays the list of installed plugins including
4461
4304
    version of plugin and a short description of each.
4468
4311
    adding new commands, providing additional network transports and
4469
4312
    customizing log output.
4470
4313
 
4471
 
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4472
 
    for further information on plugins including where to find them and how to
4473
 
    install them. Instructions are also provided there on how to write new
4474
 
    plugins using the Python programming language.
 
4314
    See the Bazaar web site, http://bazaar-vcs.org, for further
 
4315
    information on plugins including where to find them and how to
 
4316
    install them. Instructions are also provided there on how to
 
4317
    write new plugins using the Python programming language.
4475
4318
    """
4476
4319
    takes_options = ['verbose']
4477
4320
 
4492
4335
                doc = '(no description)'
4493
4336
            result.append((name_ver, doc, plugin.path()))
4494
4337
        for name_ver, doc, path in sorted(result):
4495
 
            self.outf.write("%s\n" % name_ver)
4496
 
            self.outf.write("   %s\n" % doc)
 
4338
            print name_ver
 
4339
            print '   ', doc
4497
4340
            if verbose:
4498
 
                self.outf.write("   %s\n" % path)
4499
 
            self.outf.write("\n")
 
4341
                print '   ', path
 
4342
            print
4500
4343
 
4501
4344
 
4502
4345
class cmd_testament(Command):
4503
 
    __doc__ = """Show testament (signing-form) of a revision."""
 
4346
    """Show testament (signing-form) of a revision."""
4504
4347
    takes_options = [
4505
4348
            'revision',
4506
4349
            Option('long', help='Produce long-format testament.'),
4518
4361
            b = Branch.open_containing(branch)[0]
4519
4362
        else:
4520
4363
            b = Branch.open(branch)
4521
 
        self.add_cleanup(b.lock_read().unlock)
4522
 
        if revision is None:
4523
 
            rev_id = b.last_revision()
4524
 
        else:
4525
 
            rev_id = revision[0].as_revision_id(b)
4526
 
        t = testament_class.from_revision(b.repository, rev_id)
4527
 
        if long:
4528
 
            sys.stdout.writelines(t.as_text_lines())
4529
 
        else:
4530
 
            sys.stdout.write(t.as_short_text())
 
4364
        b.lock_read()
 
4365
        try:
 
4366
            if revision is None:
 
4367
                rev_id = b.last_revision()
 
4368
            else:
 
4369
                rev_id = revision[0].as_revision_id(b)
 
4370
            t = testament_class.from_revision(b.repository, rev_id)
 
4371
            if long:
 
4372
                sys.stdout.writelines(t.as_text_lines())
 
4373
            else:
 
4374
                sys.stdout.write(t.as_short_text())
 
4375
        finally:
 
4376
            b.unlock()
4531
4377
 
4532
4378
 
4533
4379
class cmd_annotate(Command):
4534
 
    __doc__ = """Show the origin of each line in a file.
 
4380
    """Show the origin of each line in a file.
4535
4381
 
4536
4382
    This prints out the given file with an annotation on the left side
4537
4383
    indicating which revision, author and date introduced the change.
4548
4394
                     Option('long', help='Show commit date in annotations.'),
4549
4395
                     'revision',
4550
4396
                     'show-ids',
4551
 
                     'directory',
4552
4397
                     ]
4553
4398
    encoding_type = 'exact'
4554
4399
 
4555
4400
    @display_command
4556
4401
    def run(self, filename, all=False, long=False, revision=None,
4557
 
            show_ids=False, directory=None):
 
4402
            show_ids=False):
4558
4403
        from bzrlib.annotate import annotate_file, annotate_file_tree
4559
4404
        wt, branch, relpath = \
4560
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
4561
 
        if wt is not None:
4562
 
            self.add_cleanup(wt.lock_read().unlock)
4563
 
        else:
4564
 
            self.add_cleanup(branch.lock_read().unlock)
4565
 
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4566
 
        self.add_cleanup(tree.lock_read().unlock)
4567
 
        if wt is not None:
4568
 
            file_id = wt.path2id(relpath)
4569
 
        else:
4570
 
            file_id = tree.path2id(relpath)
4571
 
        if file_id is None:
4572
 
            raise errors.NotVersionedError(filename)
4573
 
        file_version = tree.inventory[file_id].revision
4574
 
        if wt is not None and revision is None:
4575
 
            # If there is a tree and we're not annotating historical
4576
 
            # versions, annotate the working tree's content.
4577
 
            annotate_file_tree(wt, file_id, self.outf, long, all,
4578
 
                show_ids=show_ids)
4579
 
        else:
4580
 
            annotate_file(branch, file_version, file_id, long, all, self.outf,
4581
 
                          show_ids=show_ids)
 
4405
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
4406
        if wt is not None:
 
4407
            wt.lock_read()
 
4408
        else:
 
4409
            branch.lock_read()
 
4410
        try:
 
4411
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
 
4412
            tree.lock_read()
 
4413
            try:
 
4414
                if wt is not None:
 
4415
                    file_id = wt.path2id(relpath)
 
4416
                else:
 
4417
                    file_id = tree.path2id(relpath)
 
4418
                if file_id is None:
 
4419
                    raise errors.NotVersionedError(filename)
 
4420
                file_version = tree.inventory[file_id].revision
 
4421
                if wt is not None and revision is None:
 
4422
                    # If there is a tree and we're not annotating historical
 
4423
                    # versions, annotate the working tree's content.
 
4424
                    annotate_file_tree(wt, file_id, self.outf, long, all,
 
4425
                        show_ids=show_ids)
 
4426
                else:
 
4427
                    annotate_file(branch, file_version, file_id, long, all,
 
4428
                        self.outf, show_ids=show_ids)
 
4429
            finally:
 
4430
                tree.unlock()
 
4431
        finally:
 
4432
            if wt is not None:
 
4433
                wt.unlock()
 
4434
            else:
 
4435
                branch.unlock()
4582
4436
 
4583
4437
 
4584
4438
class cmd_re_sign(Command):
4585
 
    __doc__ = """Create a digital signature for an existing revision."""
 
4439
    """Create a digital signature for an existing revision."""
4586
4440
    # TODO be able to replace existing ones.
4587
4441
 
4588
4442
    hidden = True # is this right ?
4589
4443
    takes_args = ['revision_id*']
4590
 
    takes_options = ['directory', 'revision']
 
4444
    takes_options = ['revision']
4591
4445
 
4592
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
4446
    def run(self, revision_id_list=None, revision=None):
4593
4447
        if revision_id_list is not None and revision is not None:
4594
4448
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4595
4449
        if revision_id_list is None and revision is None:
4596
4450
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4597
 
        b = WorkingTree.open_containing(directory)[0].branch
4598
 
        self.add_cleanup(b.lock_write().unlock)
4599
 
        return self._run(b, revision_id_list, revision)
 
4451
        b = WorkingTree.open_containing(u'.')[0].branch
 
4452
        b.lock_write()
 
4453
        try:
 
4454
            return self._run(b, revision_id_list, revision)
 
4455
        finally:
 
4456
            b.unlock()
4600
4457
 
4601
4458
    def _run(self, b, revision_id_list, revision):
4602
4459
        import bzrlib.gpg as gpg
4647
4504
 
4648
4505
 
4649
4506
class cmd_bind(Command):
4650
 
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
4651
 
    If no branch is supplied, rebind to the last bound location.
 
4507
    """Convert the current branch into a checkout of the supplied branch.
4652
4508
 
4653
4509
    Once converted into a checkout, commits must succeed on the master branch
4654
4510
    before they will be applied to the local branch.
4655
4511
 
4656
4512
    Bound branches use the nickname of its master branch unless it is set
4657
 
    locally, in which case binding will update the local nickname to be
 
4513
    locally, in which case binding will update the the local nickname to be
4658
4514
    that of the master.
4659
4515
    """
4660
4516
 
4661
4517
    _see_also = ['checkouts', 'unbind']
4662
4518
    takes_args = ['location?']
4663
 
    takes_options = ['directory']
 
4519
    takes_options = []
4664
4520
 
4665
 
    def run(self, location=None, directory=u'.'):
4666
 
        b, relpath = Branch.open_containing(directory)
 
4521
    def run(self, location=None):
 
4522
        b, relpath = Branch.open_containing(u'.')
4667
4523
        if location is None:
4668
4524
            try:
4669
4525
                location = b.get_old_bound_location()
4672
4528
                    'This format does not remember old locations.')
4673
4529
            else:
4674
4530
                if location is None:
4675
 
                    if b.get_bound_location() is not None:
4676
 
                        raise errors.BzrCommandError('Branch is already bound')
4677
 
                    else:
4678
 
                        raise errors.BzrCommandError('No location supplied '
4679
 
                            'and no previous location known')
 
4531
                    raise errors.BzrCommandError('No location supplied and no '
 
4532
                        'previous location known')
4680
4533
        b_other = Branch.open(location)
4681
4534
        try:
4682
4535
            b.bind(b_other)
4688
4541
 
4689
4542
 
4690
4543
class cmd_unbind(Command):
4691
 
    __doc__ = """Convert the current checkout into a regular branch.
 
4544
    """Convert the current checkout into a regular branch.
4692
4545
 
4693
4546
    After unbinding, the local branch is considered independent and subsequent
4694
4547
    commits will be local only.
4696
4549
 
4697
4550
    _see_also = ['checkouts', 'bind']
4698
4551
    takes_args = []
4699
 
    takes_options = ['directory']
 
4552
    takes_options = []
4700
4553
 
4701
 
    def run(self, directory=u'.'):
4702
 
        b, relpath = Branch.open_containing(directory)
 
4554
    def run(self):
 
4555
        b, relpath = Branch.open_containing(u'.')
4703
4556
        if not b.unbind():
4704
4557
            raise errors.BzrCommandError('Local branch is not bound')
4705
4558
 
4706
4559
 
4707
4560
class cmd_uncommit(Command):
4708
 
    __doc__ = """Remove the last committed revision.
 
4561
    """Remove the last committed revision.
4709
4562
 
4710
4563
    --verbose will print out what is being removed.
4711
4564
    --dry-run will go through all the motions, but not actually
4751
4604
            b = control.open_branch()
4752
4605
 
4753
4606
        if tree is not None:
4754
 
            self.add_cleanup(tree.lock_write().unlock)
 
4607
            tree.lock_write()
4755
4608
        else:
4756
 
            self.add_cleanup(b.lock_write().unlock)
4757
 
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
 
4609
            b.lock_write()
 
4610
        try:
 
4611
            return self._run(b, tree, dry_run, verbose, revision, force,
 
4612
                             local=local)
 
4613
        finally:
 
4614
            if tree is not None:
 
4615
                tree.unlock()
 
4616
            else:
 
4617
                b.unlock()
4758
4618
 
4759
4619
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4760
4620
        from bzrlib.log import log_formatter, show_log
4792
4652
                 end_revision=last_revno)
4793
4653
 
4794
4654
        if dry_run:
4795
 
            self.outf.write('Dry-run, pretending to remove'
4796
 
                            ' the above revisions.\n')
 
4655
            print 'Dry-run, pretending to remove the above revisions.'
 
4656
            if not force:
 
4657
                val = raw_input('Press <enter> to continue')
4797
4658
        else:
4798
 
            self.outf.write('The above revision(s) will be removed.\n')
4799
 
 
4800
 
        if not force:
4801
 
            if not ui.ui_factory.get_boolean('Are you sure'):
4802
 
                self.outf.write('Canceled')
4803
 
                return 0
 
4659
            print 'The above revision(s) will be removed.'
 
4660
            if not force:
 
4661
                val = raw_input('Are you sure [y/N]? ')
 
4662
                if val.lower() not in ('y', 'yes'):
 
4663
                    print 'Canceled'
 
4664
                    return 0
4804
4665
 
4805
4666
        mutter('Uncommitting from {%s} to {%s}',
4806
4667
               last_rev_id, rev_id)
4807
4668
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4808
4669
                 revno=revno, local=local)
4809
 
        self.outf.write('You can restore the old tip by running:\n'
4810
 
             '  bzr pull . -r revid:%s\n' % last_rev_id)
 
4670
        note('You can restore the old tip by running:\n'
 
4671
             '  bzr pull . -r revid:%s', last_rev_id)
4811
4672
 
4812
4673
 
4813
4674
class cmd_break_lock(Command):
4814
 
    __doc__ = """Break a dead lock.
4815
 
 
4816
 
    This command breaks a lock on a repository, branch, working directory or
4817
 
    config file.
 
4675
    """Break a dead lock on a repository, branch or working directory.
4818
4676
 
4819
4677
    CAUTION: Locks should only be broken when you are sure that the process
4820
4678
    holding the lock has been stopped.
4821
4679
 
4822
 
    You can get information on what locks are open via the 'bzr info
4823
 
    [location]' command.
 
4680
    You can get information on what locks are open via the 'bzr info' command.
4824
4681
 
4825
4682
    :Examples:
4826
4683
        bzr break-lock
4827
 
        bzr break-lock bzr+ssh://example.com/bzr/foo
4828
 
        bzr break-lock --conf ~/.bazaar
4829
4684
    """
4830
 
 
4831
4685
    takes_args = ['location?']
4832
 
    takes_options = [
4833
 
        Option('config',
4834
 
               help='LOCATION is the directory where the config lock is.'),
4835
 
        ]
4836
4686
 
4837
 
    def run(self, location=None, config=False):
 
4687
    def run(self, location=None, show=False):
4838
4688
        if location is None:
4839
4689
            location = u'.'
4840
 
        if config:
4841
 
            conf = _mod_config.LockableConfig(file_name=location)
4842
 
            conf.break_lock()
4843
 
        else:
4844
 
            control, relpath = bzrdir.BzrDir.open_containing(location)
4845
 
            try:
4846
 
                control.break_lock()
4847
 
            except NotImplementedError:
4848
 
                pass
 
4690
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4691
        try:
 
4692
            control.break_lock()
 
4693
        except NotImplementedError:
 
4694
            pass
4849
4695
 
4850
4696
 
4851
4697
class cmd_wait_until_signalled(Command):
4852
 
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4698
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4853
4699
 
4854
4700
    This just prints a line to signal when it is ready, then blocks on stdin.
4855
4701
    """
4863
4709
 
4864
4710
 
4865
4711
class cmd_serve(Command):
4866
 
    __doc__ = """Run the bzr server."""
 
4712
    """Run the bzr server."""
4867
4713
 
4868
4714
    aliases = ['server']
4869
4715
 
4870
4716
    takes_options = [
4871
4717
        Option('inet',
4872
4718
               help='Serve on stdin/out for use from inetd or sshd.'),
4873
 
        RegistryOption('protocol',
4874
 
               help="Protocol to serve.",
 
4719
        RegistryOption('protocol', 
 
4720
               help="Protocol to serve.", 
4875
4721
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
4876
4722
               value_switches=True),
4877
4723
        Option('port',
4880
4726
                    'result in a dynamically allocated port.  The default port '
4881
4727
                    'depends on the protocol.',
4882
4728
               type=str),
4883
 
        custom_help('directory',
4884
 
               help='Serve contents of this directory.'),
 
4729
        Option('directory',
 
4730
               help='Serve contents of this directory.',
 
4731
               type=unicode),
4885
4732
        Option('allow-writes',
4886
4733
               help='By default the server is a readonly server.  Supplying '
4887
4734
                    '--allow-writes enables write access to the contents of '
4888
 
                    'the served directory and below.  Note that ``bzr serve`` '
4889
 
                    'does not perform authentication, so unless some form of '
4890
 
                    'external authentication is arranged supplying this '
4891
 
                    'option leads to global uncontrolled write access to your '
4892
 
                    'file system.'
 
4735
                    'the served directory and below.'
4893
4736
                ),
4894
4737
        ]
4895
4738
 
4914
4757
 
4915
4758
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
4916
4759
            protocol=None):
4917
 
        from bzrlib import transport
 
4760
        from bzrlib.transport import get_transport, transport_server_registry
4918
4761
        if directory is None:
4919
4762
            directory = os.getcwd()
4920
4763
        if protocol is None:
4921
 
            protocol = transport.transport_server_registry.get()
 
4764
            protocol = transport_server_registry.get()
4922
4765
        host, port = self.get_host_and_port(port)
4923
4766
        url = urlutils.local_path_to_url(directory)
4924
4767
        if not allow_writes:
4925
4768
            url = 'readonly+' + url
4926
 
        t = transport.get_transport(url)
4927
 
        protocol(t, host, port, inet)
 
4769
        transport = get_transport(url)
 
4770
        protocol(transport, host, port, inet)
4928
4771
 
4929
4772
 
4930
4773
class cmd_join(Command):
4931
 
    __doc__ = """Combine a tree into its containing tree.
 
4774
    """Combine a tree into its containing tree.
4932
4775
 
4933
4776
    This command requires the target tree to be in a rich-root format.
4934
4777
 
4974
4817
 
4975
4818
 
4976
4819
class cmd_split(Command):
4977
 
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
4820
    """Split a subdirectory of a tree into a separate tree.
4978
4821
 
4979
4822
    This command will produce a target tree in a format that supports
4980
4823
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
5000
4843
 
5001
4844
 
5002
4845
class cmd_merge_directive(Command):
5003
 
    __doc__ = """Generate a merge directive for auto-merge tools.
 
4846
    """Generate a merge directive for auto-merge tools.
5004
4847
 
5005
4848
    A directive requests a merge to be performed, and also provides all the
5006
4849
    information necessary to do so.  This means it must either include a
5023
4866
    _see_also = ['send']
5024
4867
 
5025
4868
    takes_options = [
5026
 
        'directory',
5027
4869
        RegistryOption.from_kwargs('patch-type',
5028
4870
            'The type of patch to include in the directive.',
5029
4871
            title='Patch type',
5042
4884
    encoding_type = 'exact'
5043
4885
 
5044
4886
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5045
 
            sign=False, revision=None, mail_to=None, message=None,
5046
 
            directory=u'.'):
 
4887
            sign=False, revision=None, mail_to=None, message=None):
5047
4888
        from bzrlib.revision import ensure_null, NULL_REVISION
5048
4889
        include_patch, include_bundle = {
5049
4890
            'plain': (False, False),
5050
4891
            'diff': (True, False),
5051
4892
            'bundle': (True, True),
5052
4893
            }[patch_type]
5053
 
        branch = Branch.open(directory)
 
4894
        branch = Branch.open('.')
5054
4895
        stored_submit_branch = branch.get_submit_branch()
5055
4896
        if submit_branch is None:
5056
4897
            submit_branch = stored_submit_branch
5101
4942
 
5102
4943
 
5103
4944
class cmd_send(Command):
5104
 
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
4945
    """Mail or create a merge-directive for submitting changes.
5105
4946
 
5106
4947
    A merge directive provides many things needed for requesting merges:
5107
4948
 
5113
4954
      directly from the merge directive, without retrieving data from a
5114
4955
      branch.
5115
4956
 
5116
 
    `bzr send` creates a compact data set that, when applied using bzr
5117
 
    merge, has the same effect as merging from the source branch.  
5118
 
    
5119
 
    By default the merge directive is self-contained and can be applied to any
5120
 
    branch containing submit_branch in its ancestory without needing access to
5121
 
    the source branch.
5122
 
    
5123
 
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
5124
 
    revisions, but only a structured request to merge from the
5125
 
    public_location.  In that case the public_branch is needed and it must be
5126
 
    up-to-date and accessible to the recipient.  The public_branch is always
5127
 
    included if known, so that people can check it later.
5128
 
 
5129
 
    The submit branch defaults to the parent of the source branch, but can be
5130
 
    overridden.  Both submit branch and public branch will be remembered in
5131
 
    branch.conf the first time they are used for a particular branch.  The
5132
 
    source branch defaults to that containing the working directory, but can
5133
 
    be changed using --from.
5134
 
 
5135
 
    In order to calculate those changes, bzr must analyse the submit branch.
5136
 
    Therefore it is most efficient for the submit branch to be a local mirror.
5137
 
    If a public location is known for the submit_branch, that location is used
5138
 
    in the merge directive.
5139
 
 
5140
 
    The default behaviour is to send the merge directive by mail, unless -o is
5141
 
    given, in which case it is sent to a file.
 
4957
    If --no-bundle is specified, then public_branch is needed (and must be
 
4958
    up-to-date), so that the receiver can perform the merge using the
 
4959
    public_branch.  The public_branch is always included if known, so that
 
4960
    people can check it later.
 
4961
 
 
4962
    The submit branch defaults to the parent, but can be overridden.  Both
 
4963
    submit branch and public branch will be remembered if supplied.
 
4964
 
 
4965
    If a public_branch is known for the submit_branch, that public submit
 
4966
    branch is used in the merge instructions.  This means that a local mirror
 
4967
    can be used as your actual submit branch, once you have set public_branch
 
4968
    for that mirror.
5142
4969
 
5143
4970
    Mail is sent using your preferred mail program.  This should be transparent
5144
 
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
4971
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
5145
4972
    If the preferred client can't be found (or used), your editor will be used.
5146
4973
 
5147
4974
    To use a specific mail program, set the mail_client configuration option.
5148
4975
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
5149
 
    specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5150
 
    Mail.app), "mutt", and "thunderbird"; generic options are "default",
5151
 
    "editor", "emacsclient", "mapi", and "xdg-email".  Plugins may also add
5152
 
    supported clients.
 
4976
    specific clients are "claws", "evolution", "kmail", "mutt", and
 
4977
    "thunderbird"; generic options are "default", "editor", "emacsclient",
 
4978
    "mapi", and "xdg-email".  Plugins may also add supported clients.
5153
4979
 
5154
4980
    If mail is being sent, a to address is required.  This can be supplied
5155
4981
    either on the commandline, by setting the submit_to configuration
5164
4990
 
5165
4991
    The merge directives created by bzr send may be applied using bzr merge or
5166
4992
    bzr pull by specifying a file containing a merge directive as the location.
5167
 
 
5168
 
    bzr send makes extensive use of public locations to map local locations into
5169
 
    URLs that can be used by other people.  See `bzr help configuration` to
5170
 
    set them, and use `bzr info` to display them.
5171
4993
    """
5172
4994
 
5173
4995
    encoding_type = 'exact'
5189
5011
               short_name='f',
5190
5012
               type=unicode),
5191
5013
        Option('output', short_name='o',
5192
 
               help='Write merge directive to this file or directory; '
 
5014
               help='Write merge directive to this file; '
5193
5015
                    'use - for stdout.',
5194
5016
               type=unicode),
5195
5017
        Option('strict',
5218
5040
 
5219
5041
 
5220
5042
class cmd_bundle_revisions(cmd_send):
5221
 
    __doc__ = """Create a merge-directive for submitting changes.
 
5043
    """Create a merge-directive for submitting changes.
5222
5044
 
5223
5045
    A merge directive provides many things needed for requesting merges:
5224
5046
 
5291
5113
 
5292
5114
 
5293
5115
class cmd_tag(Command):
5294
 
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5116
    """Create, remove or modify a tag naming a revision.
5295
5117
 
5296
5118
    Tags give human-meaningful names to revisions.  Commands that take a -r
5297
5119
    (--revision) option can be given -rtag:X, where X is any previously
5305
5127
 
5306
5128
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
5307
5129
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5308
 
 
5309
 
    If no tag name is specified it will be determined through the 
5310
 
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
5311
 
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
5312
 
    details.
5313
5130
    """
5314
5131
 
5315
5132
    _see_also = ['commit', 'tags']
5316
 
    takes_args = ['tag_name?']
 
5133
    takes_args = ['tag_name']
5317
5134
    takes_options = [
5318
5135
        Option('delete',
5319
5136
            help='Delete this tag rather than placing it.',
5320
5137
            ),
5321
 
        custom_help('directory',
5322
 
            help='Branch in which to place the tag.'),
 
5138
        Option('directory',
 
5139
            help='Branch in which to place the tag.',
 
5140
            short_name='d',
 
5141
            type=unicode,
 
5142
            ),
5323
5143
        Option('force',
5324
5144
            help='Replace existing tags.',
5325
5145
            ),
5326
5146
        'revision',
5327
5147
        ]
5328
5148
 
5329
 
    def run(self, tag_name=None,
 
5149
    def run(self, tag_name,
5330
5150
            delete=None,
5331
5151
            directory='.',
5332
5152
            force=None,
5333
5153
            revision=None,
5334
5154
            ):
5335
5155
        branch, relpath = Branch.open_containing(directory)
5336
 
        self.add_cleanup(branch.lock_write().unlock)
5337
 
        if delete:
5338
 
            if tag_name is None:
5339
 
                raise errors.BzrCommandError("No tag specified to delete.")
5340
 
            branch.tags.delete_tag(tag_name)
5341
 
            self.outf.write('Deleted tag %s.\n' % tag_name)
5342
 
        else:
5343
 
            if revision:
5344
 
                if len(revision) != 1:
5345
 
                    raise errors.BzrCommandError(
5346
 
                        "Tags can only be placed on a single revision, "
5347
 
                        "not on a range")
5348
 
                revision_id = revision[0].as_revision_id(branch)
 
5156
        branch.lock_write()
 
5157
        try:
 
5158
            if delete:
 
5159
                branch.tags.delete_tag(tag_name)
 
5160
                self.outf.write('Deleted tag %s.\n' % tag_name)
5349
5161
            else:
5350
 
                revision_id = branch.last_revision()
5351
 
            if tag_name is None:
5352
 
                tag_name = branch.automatic_tag_name(revision_id)
5353
 
                if tag_name is None:
5354
 
                    raise errors.BzrCommandError(
5355
 
                        "Please specify a tag name.")
5356
 
            if (not force) and branch.tags.has_tag(tag_name):
5357
 
                raise errors.TagAlreadyExists(tag_name)
5358
 
            branch.tags.set_tag(tag_name, revision_id)
5359
 
            self.outf.write('Created tag %s.\n' % tag_name)
 
5162
                if revision:
 
5163
                    if len(revision) != 1:
 
5164
                        raise errors.BzrCommandError(
 
5165
                            "Tags can only be placed on a single revision, "
 
5166
                            "not on a range")
 
5167
                    revision_id = revision[0].as_revision_id(branch)
 
5168
                else:
 
5169
                    revision_id = branch.last_revision()
 
5170
                if (not force) and branch.tags.has_tag(tag_name):
 
5171
                    raise errors.TagAlreadyExists(tag_name)
 
5172
                branch.tags.set_tag(tag_name, revision_id)
 
5173
                self.outf.write('Created tag %s.\n' % tag_name)
 
5174
        finally:
 
5175
            branch.unlock()
5360
5176
 
5361
5177
 
5362
5178
class cmd_tags(Command):
5363
 
    __doc__ = """List tags.
 
5179
    """List tags.
5364
5180
 
5365
5181
    This command shows a table of tag names and the revisions they reference.
5366
5182
    """
5367
5183
 
5368
5184
    _see_also = ['tag']
5369
5185
    takes_options = [
5370
 
        custom_help('directory',
5371
 
            help='Branch whose tags should be displayed.'),
 
5186
        Option('directory',
 
5187
            help='Branch whose tags should be displayed.',
 
5188
            short_name='d',
 
5189
            type=unicode,
 
5190
            ),
5372
5191
        RegistryOption.from_kwargs('sort',
5373
5192
            'Sort tags by different criteria.', title='Sorting',
5374
5193
            alpha='Sort tags lexicographically (default).',
5391
5210
        if not tags:
5392
5211
            return
5393
5212
 
5394
 
        self.add_cleanup(branch.lock_read().unlock)
5395
 
        if revision:
5396
 
            graph = branch.repository.get_graph()
5397
 
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
5398
 
            revid1, revid2 = rev1.rev_id, rev2.rev_id
5399
 
            # only show revisions between revid1 and revid2 (inclusive)
5400
 
            tags = [(tag, revid) for tag, revid in tags if
5401
 
                graph.is_between(revid, revid1, revid2)]
5402
 
        if sort == 'alpha':
5403
 
            tags.sort()
5404
 
        elif sort == 'time':
5405
 
            timestamps = {}
5406
 
            for tag, revid in tags:
5407
 
                try:
5408
 
                    revobj = branch.repository.get_revision(revid)
5409
 
                except errors.NoSuchRevision:
5410
 
                    timestamp = sys.maxint # place them at the end
5411
 
                else:
5412
 
                    timestamp = revobj.timestamp
5413
 
                timestamps[revid] = timestamp
5414
 
            tags.sort(key=lambda x: timestamps[x[1]])
5415
 
        if not show_ids:
5416
 
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5417
 
            for index, (tag, revid) in enumerate(tags):
5418
 
                try:
5419
 
                    revno = branch.revision_id_to_dotted_revno(revid)
5420
 
                    if isinstance(revno, tuple):
5421
 
                        revno = '.'.join(map(str, revno))
5422
 
                except errors.NoSuchRevision:
5423
 
                    # Bad tag data/merges can lead to tagged revisions
5424
 
                    # which are not in this branch. Fail gracefully ...
5425
 
                    revno = '?'
5426
 
                tags[index] = (tag, revno)
5427
 
        self.cleanup_now()
 
5213
        branch.lock_read()
 
5214
        try:
 
5215
            if revision:
 
5216
                graph = branch.repository.get_graph()
 
5217
                rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5218
                revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5219
                # only show revisions between revid1 and revid2 (inclusive)
 
5220
                tags = [(tag, revid) for tag, revid in tags if
 
5221
                    graph.is_between(revid, revid1, revid2)]
 
5222
            if sort == 'alpha':
 
5223
                tags.sort()
 
5224
            elif sort == 'time':
 
5225
                timestamps = {}
 
5226
                for tag, revid in tags:
 
5227
                    try:
 
5228
                        revobj = branch.repository.get_revision(revid)
 
5229
                    except errors.NoSuchRevision:
 
5230
                        timestamp = sys.maxint # place them at the end
 
5231
                    else:
 
5232
                        timestamp = revobj.timestamp
 
5233
                    timestamps[revid] = timestamp
 
5234
                tags.sort(key=lambda x: timestamps[x[1]])
 
5235
            if not show_ids:
 
5236
                # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
5237
                for index, (tag, revid) in enumerate(tags):
 
5238
                    try:
 
5239
                        revno = branch.revision_id_to_dotted_revno(revid)
 
5240
                        if isinstance(revno, tuple):
 
5241
                            revno = '.'.join(map(str, revno))
 
5242
                    except errors.NoSuchRevision:
 
5243
                        # Bad tag data/merges can lead to tagged revisions
 
5244
                        # which are not in this branch. Fail gracefully ...
 
5245
                        revno = '?'
 
5246
                    tags[index] = (tag, revno)
 
5247
        finally:
 
5248
            branch.unlock()
5428
5249
        for tag, revspec in tags:
5429
5250
            self.outf.write('%-20s %s\n' % (tag, revspec))
5430
5251
 
5431
5252
 
5432
5253
class cmd_reconfigure(Command):
5433
 
    __doc__ = """Reconfigure the type of a bzr directory.
 
5254
    """Reconfigure the type of a bzr directory.
5434
5255
 
5435
5256
    A target configuration must be specified.
5436
5257
 
5521
5342
 
5522
5343
 
5523
5344
class cmd_switch(Command):
5524
 
    __doc__ = """Set the branch of a checkout and update.
 
5345
    """Set the branch of a checkout and update.
5525
5346
 
5526
5347
    For lightweight checkouts, this changes the branch being referenced.
5527
5348
    For heavyweight checkouts, this checks that there are no local commits
5539
5360
    /path/to/newbranch.
5540
5361
 
5541
5362
    Bound branches use the nickname of its master branch unless it is set
5542
 
    locally, in which case switching will update the local nickname to be
 
5363
    locally, in which case switching will update the the local nickname to be
5543
5364
    that of the master.
5544
5365
    """
5545
5366
 
5546
 
    takes_args = ['to_location?']
5547
 
    takes_options = ['directory',
5548
 
                     Option('force',
 
5367
    takes_args = ['to_location']
 
5368
    takes_options = [Option('force',
5549
5369
                        help='Switch even if local commits will be lost.'),
5550
 
                     'revision',
5551
5370
                     Option('create-branch', short_name='b',
5552
5371
                        help='Create the target branch from this one before'
5553
5372
                             ' switching to it.'),
5554
 
                    ]
 
5373
                     ]
5555
5374
 
5556
 
    def run(self, to_location=None, force=False, create_branch=False,
5557
 
            revision=None, directory=u'.'):
 
5375
    def run(self, to_location, force=False, create_branch=False):
5558
5376
        from bzrlib import switch
5559
 
        tree_location = directory
5560
 
        revision = _get_one_revision('switch', revision)
 
5377
        tree_location = '.'
5561
5378
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5562
 
        if to_location is None:
5563
 
            if revision is None:
5564
 
                raise errors.BzrCommandError('You must supply either a'
5565
 
                                             ' revision or a location')
5566
 
            to_location = tree_location
5567
5379
        try:
5568
5380
            branch = control_dir.open_branch()
5569
5381
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5574
5386
            if branch is None:
5575
5387
                raise errors.BzrCommandError('cannot create branch without'
5576
5388
                                             ' source branch')
5577
 
            to_location = directory_service.directories.dereference(
5578
 
                              to_location)
5579
5389
            if '/' not in to_location and '\\' not in to_location:
5580
5390
                # This path is meant to be relative to the existing branch
5581
5391
                this_url = self._get_branch_location(control_dir)
5583
5393
            to_branch = branch.bzrdir.sprout(to_location,
5584
5394
                                 possible_transports=[branch.bzrdir.root_transport],
5585
5395
                                 source_branch=branch).open_branch()
 
5396
            # try:
 
5397
            #     from_branch = control_dir.open_branch()
 
5398
            # except errors.NotBranchError:
 
5399
            #     raise BzrCommandError('Cannot create a branch from this'
 
5400
            #         ' location when we cannot open this branch')
 
5401
            # from_branch.bzrdir.sprout(
 
5402
            pass
5586
5403
        else:
5587
5404
            try:
5588
5405
                to_branch = Branch.open(to_location)
5590
5407
                this_url = self._get_branch_location(control_dir)
5591
5408
                to_branch = Branch.open(
5592
5409
                    urlutils.join(this_url, '..', to_location))
5593
 
        if revision is not None:
5594
 
            revision = revision.as_revision_id(to_branch)
5595
 
        switch.switch(control_dir, to_branch, force, revision_id=revision)
 
5410
        switch.switch(control_dir, to_branch, force)
5596
5411
        if had_explicit_nick:
5597
5412
            branch = control_dir.open_branch() #get the new branch!
5598
5413
            branch.nick = to_branch.nick
5618
5433
 
5619
5434
 
5620
5435
class cmd_view(Command):
5621
 
    __doc__ = """Manage filtered views.
 
5436
    """Manage filtered views.
5622
5437
 
5623
5438
    Views provide a mask over the tree so that users can focus on
5624
5439
    a subset of a tree when doing their work. After creating a view,
5704
5519
            name=None,
5705
5520
            switch=None,
5706
5521
            ):
5707
 
        tree, file_list = WorkingTree.open_containing_paths(file_list,
5708
 
            apply_view=False)
 
5522
        tree, file_list = tree_files(file_list, apply_view=False)
5709
5523
        current_view, view_dict = tree.views.get_view_info()
5710
5524
        if name is None:
5711
5525
            name = current_view
5773
5587
 
5774
5588
 
5775
5589
class cmd_hooks(Command):
5776
 
    __doc__ = """Show hooks."""
 
5590
    """Show hooks."""
5777
5591
 
5778
5592
    hidden = True
5779
5593
 
5792
5606
                    self.outf.write("    <no hooks installed>\n")
5793
5607
 
5794
5608
 
5795
 
class cmd_remove_branch(Command):
5796
 
    __doc__ = """Remove a branch.
5797
 
 
5798
 
    This will remove the branch from the specified location but 
5799
 
    will keep any working tree or repository in place.
5800
 
 
5801
 
    :Examples:
5802
 
 
5803
 
      Remove the branch at repo/trunk::
5804
 
 
5805
 
        bzr remove-branch repo/trunk
5806
 
 
5807
 
    """
5808
 
 
5809
 
    takes_args = ["location?"]
5810
 
 
5811
 
    aliases = ["rmbranch"]
5812
 
 
5813
 
    def run(self, location=None):
5814
 
        if location is None:
5815
 
            location = "."
5816
 
        branch = Branch.open_containing(location)[0]
5817
 
        branch.bzrdir.destroy_branch()
5818
 
        
5819
 
 
5820
5609
class cmd_shelve(Command):
5821
 
    __doc__ = """Temporarily set aside some changes from the current tree.
 
5610
    """Temporarily set aside some changes from the current tree.
5822
5611
 
5823
5612
    Shelve allows you to temporarily put changes you've made "on the shelf",
5824
5613
    ie. out of the way, until a later time when you can bring them back from
5845
5634
    takes_args = ['file*']
5846
5635
 
5847
5636
    takes_options = [
5848
 
        'directory',
5849
5637
        'revision',
5850
5638
        Option('all', help='Shelve all changes.'),
5851
5639
        'message',
5860
5648
    _see_also = ['unshelve']
5861
5649
 
5862
5650
    def run(self, revision=None, all=False, file_list=None, message=None,
5863
 
            writer=None, list=False, destroy=False, directory=u'.'):
 
5651
            writer=None, list=False, destroy=False):
5864
5652
        if list:
5865
5653
            return self.run_for_list()
5866
5654
        from bzrlib.shelf_ui import Shelver
5868
5656
            writer = bzrlib.option.diff_writer_registry.get()
5869
5657
        try:
5870
5658
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5871
 
                file_list, message, destroy=destroy, directory=directory)
 
5659
                file_list, message, destroy=destroy)
5872
5660
            try:
5873
5661
                shelver.run()
5874
5662
            finally:
5875
 
                shelver.finalize()
 
5663
                shelver.work_tree.unlock()
5876
5664
        except errors.UserAbort:
5877
5665
            return 0
5878
5666
 
5879
5667
    def run_for_list(self):
5880
5668
        tree = WorkingTree.open_containing('.')[0]
5881
 
        self.add_cleanup(tree.lock_read().unlock)
5882
 
        manager = tree.get_shelf_manager()
5883
 
        shelves = manager.active_shelves()
5884
 
        if len(shelves) == 0:
5885
 
            note('No shelved changes.')
5886
 
            return 0
5887
 
        for shelf_id in reversed(shelves):
5888
 
            message = manager.get_metadata(shelf_id).get('message')
5889
 
            if message is None:
5890
 
                message = '<no message>'
5891
 
            self.outf.write('%3d: %s\n' % (shelf_id, message))
5892
 
        return 1
 
5669
        tree.lock_read()
 
5670
        try:
 
5671
            manager = tree.get_shelf_manager()
 
5672
            shelves = manager.active_shelves()
 
5673
            if len(shelves) == 0:
 
5674
                note('No shelved changes.')
 
5675
                return 0
 
5676
            for shelf_id in reversed(shelves):
 
5677
                message = manager.get_metadata(shelf_id).get('message')
 
5678
                if message is None:
 
5679
                    message = '<no message>'
 
5680
                self.outf.write('%3d: %s\n' % (shelf_id, message))
 
5681
            return 1
 
5682
        finally:
 
5683
            tree.unlock()
5893
5684
 
5894
5685
 
5895
5686
class cmd_unshelve(Command):
5896
 
    __doc__ = """Restore shelved changes.
 
5687
    """Restore shelved changes.
5897
5688
 
5898
5689
    By default, the most recently shelved changes are restored. However if you
5899
5690
    specify a shelf by id those changes will be restored instead.  This works
5902
5693
 
5903
5694
    takes_args = ['shelf_id?']
5904
5695
    takes_options = [
5905
 
        'directory',
5906
5696
        RegistryOption.from_kwargs(
5907
5697
            'action', help="The action to perform.",
5908
5698
            enum_switch=False, value_switches=True,
5909
5699
            apply="Apply changes and remove from the shelf.",
5910
5700
            dry_run="Show changes, but do not apply or remove them.",
5911
 
            preview="Instead of unshelving the changes, show the diff that "
5912
 
                    "would result from unshelving.",
5913
 
            delete_only="Delete changes without applying them.",
5914
 
            keep="Apply changes but don't delete them.",
 
5701
            delete_only="Delete changes without applying them."
5915
5702
        )
5916
5703
    ]
5917
5704
    _see_also = ['shelve']
5918
5705
 
5919
 
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
5706
    def run(self, shelf_id=None, action='apply'):
5920
5707
        from bzrlib.shelf_ui import Unshelver
5921
 
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
5708
        unshelver = Unshelver.from_args(shelf_id, action)
5922
5709
        try:
5923
5710
            unshelver.run()
5924
5711
        finally:
5926
5713
 
5927
5714
 
5928
5715
class cmd_clean_tree(Command):
5929
 
    __doc__ = """Remove unwanted files from working tree.
 
5716
    """Remove unwanted files from working tree.
5930
5717
 
5931
5718
    By default, only unknown files, not ignored files, are deleted.  Versioned
5932
5719
    files are never deleted.
5940
5727
 
5941
5728
    To check what clean-tree will do, use --dry-run.
5942
5729
    """
5943
 
    takes_options = ['directory',
5944
 
                     Option('ignored', help='Delete all ignored files.'),
 
5730
    takes_options = [Option('ignored', help='Delete all ignored files.'),
5945
5731
                     Option('detritus', help='Delete conflict files, merge'
5946
5732
                            ' backups, and failed selftest dirs.'),
5947
5733
                     Option('unknown',
5950
5736
                            ' deleting them.'),
5951
5737
                     Option('force', help='Do not prompt before deleting.')]
5952
5738
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5953
 
            force=False, directory=u'.'):
 
5739
            force=False):
5954
5740
        from bzrlib.clean_tree import clean_tree
5955
5741
        if not (unknown or ignored or detritus):
5956
5742
            unknown = True
5957
5743
        if dry_run:
5958
5744
            force = True
5959
 
        clean_tree(directory, unknown=unknown, ignored=ignored,
5960
 
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5745
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5746
                   dry_run=dry_run, no_prompt=force)
5961
5747
 
5962
5748
 
5963
5749
class cmd_reference(Command):
5964
 
    __doc__ = """list, view and set branch locations for nested trees.
 
5750
    """list, view and set branch locations for nested trees.
5965
5751
 
5966
5752
    If no arguments are provided, lists the branch locations for nested trees.
5967
5753
    If one argument is provided, display the branch location for that tree.
6007
5793
            self.outf.write('%s %s\n' % (path, location))
6008
5794
 
6009
5795
 
6010
 
def _register_lazy_builtins():
6011
 
    # register lazy builtins from other modules; called at startup and should
6012
 
    # be only called once.
6013
 
    for (name, aliases, module_name) in [
6014
 
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6015
 
        ('cmd_dpush', [], 'bzrlib.foreign'),
6016
 
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6017
 
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6018
 
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6019
 
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6020
 
        ]:
6021
 
        builtin_command_registry.register_lazy(name, aliases, module_name)
 
5796
# these get imported and then picked up by the scan for cmd_*
 
5797
# TODO: Some more consistent way to split command definitions across files;
 
5798
# we do need to load at least some information about them to know of
 
5799
# aliases.  ideally we would avoid loading the implementation until the
 
5800
# details were needed.
 
5801
from bzrlib.cmd_version_info import cmd_version_info
 
5802
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
5803
from bzrlib.bundle.commands import (
 
5804
    cmd_bundle_info,
 
5805
    )
 
5806
from bzrlib.foreign import cmd_dpush
 
5807
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
5808
from bzrlib.weave_commands import cmd_versionedfile_list, \
 
5809
        cmd_weave_plan_merge, cmd_weave_merge_text