~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: John Arbash Meinel
  • Date: 2010-08-23 19:10:35 UTC
  • mto: This revision was merged to the branch mainline in revision 5390.
  • Revision ID: john@arbash-meinel.com-20100823191035-57bojnmqw54nutsz
switch 'x += 1' to 'x = x + 1' to deal with brain-damaged old versions of pyrex.

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
23
 
import codecs
24
23
import cStringIO
25
24
import sys
26
25
import time
60
59
from bzrlib.workingtree import WorkingTree
61
60
""")
62
61
 
63
 
from bzrlib.commands import Command, display_command
 
62
from bzrlib.commands import (
 
63
    Command,
 
64
    builtin_command_registry,
 
65
    display_command,
 
66
    )
64
67
from bzrlib.option import (
65
68
    ListOption,
66
69
    Option,
71
74
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
72
75
 
73
76
 
 
77
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
74
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
75
79
    apply_view=True):
76
 
    try:
77
 
        return internal_tree_files(file_list, default_branch, canonicalize,
78
 
            apply_view)
79
 
    except errors.FileInWrongBranch, e:
80
 
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
81
 
                                     (e.path, file_list[0]))
 
80
    return internal_tree_files(file_list, default_branch, canonicalize,
 
81
        apply_view)
82
82
 
83
83
 
84
84
def tree_files_for_add(file_list):
148
148
 
149
149
# XXX: Bad function name; should possibly also be a class method of
150
150
# WorkingTree rather than a function.
 
151
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
151
152
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
152
153
    apply_view=True):
153
154
    """Convert command-line paths to a WorkingTree and relative paths.
154
155
 
 
156
    Deprecated: use WorkingTree.open_containing_paths instead.
 
157
 
155
158
    This is typically used for command-line processors that take one or
156
159
    more filenames, and infer the workingtree that contains them.
157
160
 
167
170
 
168
171
    :return: workingtree, [relative_paths]
169
172
    """
170
 
    if file_list is None or len(file_list) == 0:
171
 
        tree = WorkingTree.open_containing(default_branch)[0]
172
 
        if tree.supports_views() and apply_view:
173
 
            view_files = tree.views.lookup_view()
174
 
            if view_files:
175
 
                file_list = view_files
176
 
                view_str = views.view_display_str(view_files)
177
 
                note("Ignoring files outside view. View is %s" % view_str)
178
 
        return tree, file_list
179
 
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
180
 
    return tree, safe_relpath_files(tree, file_list, canonicalize,
181
 
        apply_view=apply_view)
182
 
 
183
 
 
184
 
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
185
 
    """Convert file_list into a list of relpaths in tree.
186
 
 
187
 
    :param tree: A tree to operate on.
188
 
    :param file_list: A list of user provided paths or None.
189
 
    :param apply_view: if True and a view is set, apply it or check that
190
 
        specified files are within it
191
 
    :return: A list of relative paths.
192
 
    :raises errors.PathNotChild: When a provided path is in a different tree
193
 
        than tree.
194
 
    """
195
 
    if file_list is None:
196
 
        return None
197
 
    if tree.supports_views() and apply_view:
198
 
        view_files = tree.views.lookup_view()
199
 
    else:
200
 
        view_files = []
201
 
    new_list = []
202
 
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
203
 
    # doesn't - fix that up here before we enter the loop.
204
 
    if canonicalize:
205
 
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
206
 
    else:
207
 
        fixer = tree.relpath
208
 
    for filename in file_list:
209
 
        try:
210
 
            relpath = fixer(osutils.dereference_path(filename))
211
 
            if  view_files and not osutils.is_inside_any(view_files, relpath):
212
 
                raise errors.FileOutsideView(filename, view_files)
213
 
            new_list.append(relpath)
214
 
        except errors.PathNotChild:
215
 
            raise errors.FileInWrongBranch(tree.branch, filename)
216
 
    return new_list
 
173
    return WorkingTree.open_containing_paths(
 
174
        file_list, default_directory='.',
 
175
        canonicalize=True,
 
176
        apply_view=True)
217
177
 
218
178
 
219
179
def _get_view_info_for_change_reporter(tree):
228
188
    return view_info
229
189
 
230
190
 
 
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
 
231
199
# TODO: Make sure no commands unconditionally use the working directory as a
232
200
# branch.  If a filename argument is used, the first of them should be used to
233
201
# specify the branch.  (Perhaps this can be factored out into some kind of
235
203
# opens the branch?)
236
204
 
237
205
class cmd_status(Command):
238
 
    """Display status summary.
 
206
    __doc__ = """Display status summary.
239
207
 
240
208
    This reports on versioned and unknown files, reporting them
241
209
    grouped by state.  Possible states are:
311
279
            raise errors.BzrCommandError('bzr status --revision takes exactly'
312
280
                                         ' one or two revision specifiers')
313
281
 
314
 
        tree, relfile_list = tree_files(file_list)
 
282
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
315
283
        # Avoid asking for specific files when that is not needed.
316
284
        if relfile_list == ['']:
317
285
            relfile_list = None
328
296
 
329
297
 
330
298
class cmd_cat_revision(Command):
331
 
    """Write out metadata for a revision.
 
299
    __doc__ = """Write out metadata for a revision.
332
300
 
333
301
    The revision to print can either be specified by a specific
334
302
    revision identifier, or you can use --revision.
336
304
 
337
305
    hidden = True
338
306
    takes_args = ['revision_id?']
339
 
    takes_options = ['revision']
 
307
    takes_options = ['directory', 'revision']
340
308
    # cat-revision is more for frontends so should be exact
341
309
    encoding = 'strict'
342
310
 
 
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
 
343
319
    @display_command
344
 
    def run(self, revision_id=None, revision=None):
 
320
    def run(self, revision_id=None, revision=None, directory=u'.'):
345
321
        if revision_id is not None and revision is not None:
346
322
            raise errors.BzrCommandError('You can only supply one of'
347
323
                                         ' revision_id or --revision')
348
324
        if revision_id is None and revision is None:
349
325
            raise errors.BzrCommandError('You must supply either'
350
326
                                         ' --revision or a revision_id')
351
 
        b = WorkingTree.open_containing(u'.')[0].branch
352
 
 
353
 
        # TODO: jam 20060112 should cat-revision always output utf-8?
354
 
        if revision_id is not None:
355
 
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
356
 
            try:
357
 
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
358
 
            except errors.NoSuchRevision:
359
 
                msg = "The repository %s contains no revision %s." % (b.repository.base,
360
 
                    revision_id)
361
 
                raise errors.BzrCommandError(msg)
362
 
        elif revision is not None:
363
 
            for rev in revision:
364
 
                if rev is None:
365
 
                    raise errors.BzrCommandError('You cannot specify a NULL'
366
 
                                                 ' revision.')
367
 
                rev_id = rev.as_revision_id(b)
368
 
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
369
 
 
 
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
        
370
355
 
371
356
class cmd_dump_btree(Command):
372
 
    """Dump the contents of a btree index file to stdout.
 
357
    __doc__ = """Dump the contents of a btree index file to stdout.
373
358
 
374
359
    PATH is a btree index file, it can be any URL. This includes things like
375
360
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
439
424
        for node in bt.iter_all_entries():
440
425
            # Node is made up of:
441
426
            # (index, key, value, [references])
442
 
            refs_as_tuples = static_tuple.as_tuples(node[3])
 
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)
443
433
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
444
434
            self.outf.write('%s\n' % (as_tuple,))
445
435
 
446
436
 
447
437
class cmd_remove_tree(Command):
448
 
    """Remove the working tree from a given branch/checkout.
 
438
    __doc__ = """Remove the working tree from a given branch/checkout.
449
439
 
450
440
    Since a lightweight checkout is little more than a working tree
451
441
    this will refuse to run against one.
457
447
    takes_options = [
458
448
        Option('force',
459
449
               help='Remove the working tree even if it has '
460
 
                    'uncommitted changes.'),
 
450
                    'uncommitted or shelved changes.'),
461
451
        ]
462
452
 
463
453
    def run(self, location_list, force=False):
477
467
            if not force:
478
468
                if (working.has_changes()):
479
469
                    raise errors.UncommittedChanges(working)
 
470
                if working.get_shelf_manager().last_shelf() is not None:
 
471
                    raise errors.ShelvedChanges(working)
480
472
 
481
 
            working_path = working.bzrdir.root_transport.base
482
 
            branch_path = working.branch.bzrdir.root_transport.base
483
 
            if working_path != branch_path:
 
473
            if working.user_url != working.branch.user_url:
484
474
                raise errors.BzrCommandError("You cannot remove the working tree"
485
475
                                             " from a lightweight checkout")
486
476
 
488
478
 
489
479
 
490
480
class cmd_revno(Command):
491
 
    """Show current revision number.
 
481
    __doc__ = """Show current revision number.
492
482
 
493
483
    This is equal to the number of revisions on this branch.
494
484
    """
504
494
        if tree:
505
495
            try:
506
496
                wt = WorkingTree.open_containing(location)[0]
507
 
                wt.lock_read()
 
497
                self.add_cleanup(wt.lock_read().unlock)
508
498
            except (errors.NoWorkingTree, errors.NotLocalUrl):
509
499
                raise errors.NoWorkingTree(location)
510
 
            self.add_cleanup(wt.unlock)
511
500
            revid = wt.last_revision()
512
501
            try:
513
502
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
516
505
            revno = ".".join(str(n) for n in revno_t)
517
506
        else:
518
507
            b = Branch.open_containing(location)[0]
519
 
            b.lock_read()
520
 
            self.add_cleanup(b.unlock)
 
508
            self.add_cleanup(b.lock_read().unlock)
521
509
            revno = b.revno()
522
510
        self.cleanup_now()
523
511
        self.outf.write(str(revno) + '\n')
524
512
 
525
513
 
526
514
class cmd_revision_info(Command):
527
 
    """Show revision number and revision id for a given revision identifier.
 
515
    __doc__ = """Show revision number and revision id for a given revision identifier.
528
516
    """
529
517
    hidden = True
530
518
    takes_args = ['revision_info*']
531
519
    takes_options = [
532
520
        'revision',
533
 
        Option('directory',
 
521
        custom_help('directory',
534
522
            help='Branch to examine, '
535
 
                 'rather than the one containing the working directory.',
536
 
            short_name='d',
537
 
            type=unicode,
538
 
            ),
 
523
                 'rather than the one containing the working directory.'),
539
524
        Option('tree', help='Show revno of working tree'),
540
525
        ]
541
526
 
546
531
        try:
547
532
            wt = WorkingTree.open_containing(directory)[0]
548
533
            b = wt.branch
549
 
            wt.lock_read()
550
 
            self.add_cleanup(wt.unlock)
 
534
            self.add_cleanup(wt.lock_read().unlock)
551
535
        except (errors.NoWorkingTree, errors.NotLocalUrl):
552
536
            wt = None
553
537
            b = Branch.open_containing(directory)[0]
554
 
            b.lock_read()
555
 
            self.add_cleanup(b.unlock)
 
538
            self.add_cleanup(b.lock_read().unlock)
556
539
        revision_ids = []
557
540
        if revision is not None:
558
541
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
586
569
 
587
570
 
588
571
class cmd_add(Command):
589
 
    """Add specified files or directories.
 
572
    __doc__ = """Add specified files or directories.
590
573
 
591
574
    In non-recursive mode, all the named items are added, regardless
592
575
    of whether they were previously ignored.  A warning is given if
657
640
                should_print=(not is_quiet()))
658
641
 
659
642
        if base_tree:
660
 
            base_tree.lock_read()
661
 
            self.add_cleanup(base_tree.unlock)
 
643
            self.add_cleanup(base_tree.lock_read().unlock)
662
644
        tree, file_list = tree_files_for_add(file_list)
663
645
        added, ignored = tree.smart_add(file_list, not
664
646
            no_recurse, action=action, save=not dry_run)
672
654
 
673
655
 
674
656
class cmd_mkdir(Command):
675
 
    """Create a new versioned directory.
 
657
    __doc__ = """Create a new versioned directory.
676
658
 
677
659
    This is equivalent to creating the directory and then adding it.
678
660
    """
682
664
 
683
665
    def run(self, dir_list):
684
666
        for d in dir_list:
685
 
            os.mkdir(d)
686
667
            wt, dd = WorkingTree.open_containing(d)
687
 
            wt.add([dd])
688
 
            self.outf.write('added %s\n' % 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)
689
676
 
690
677
 
691
678
class cmd_relpath(Command):
692
 
    """Show path of a file relative to root"""
 
679
    __doc__ = """Show path of a file relative to root"""
693
680
 
694
681
    takes_args = ['filename']
695
682
    hidden = True
704
691
 
705
692
 
706
693
class cmd_inventory(Command):
707
 
    """Show inventory of the current working copy or a revision.
 
694
    __doc__ = """Show inventory of the current working copy or a revision.
708
695
 
709
696
    It is possible to limit the output to a particular entry
710
697
    type using the --kind option.  For example: --kind file.
730
717
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
731
718
 
732
719
        revision = _get_one_revision('inventory', revision)
733
 
        work_tree, file_list = tree_files(file_list)
734
 
        work_tree.lock_read()
735
 
        self.add_cleanup(work_tree.unlock)
 
720
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
 
721
        self.add_cleanup(work_tree.lock_read().unlock)
736
722
        if revision is not None:
737
723
            tree = revision.as_tree(work_tree.branch)
738
724
 
739
725
            extra_trees = [work_tree]
740
 
            tree.lock_read()
741
 
            self.add_cleanup(tree.unlock)
 
726
            self.add_cleanup(tree.lock_read().unlock)
742
727
        else:
743
728
            tree = work_tree
744
729
            extra_trees = []
765
750
 
766
751
 
767
752
class cmd_mv(Command):
768
 
    """Move or rename a file.
 
753
    __doc__ = """Move or rename a file.
769
754
 
770
755
    :Usage:
771
756
        bzr mv OLDNAME NEWNAME
803
788
            names_list = []
804
789
        if len(names_list) < 2:
805
790
            raise errors.BzrCommandError("missing file argument")
806
 
        tree, rel_names = tree_files(names_list, canonicalize=False)
807
 
        tree.lock_tree_write()
808
 
        self.add_cleanup(tree.unlock)
 
791
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
 
792
        self.add_cleanup(tree.lock_tree_write().unlock)
809
793
        self._run(tree, names_list, rel_names, after)
810
794
 
811
795
    def run_auto(self, names_list, after, dry_run):
815
799
        if after:
816
800
            raise errors.BzrCommandError('--after cannot be specified with'
817
801
                                         ' --auto.')
818
 
        work_tree, file_list = tree_files(names_list, default_branch='.')
819
 
        work_tree.lock_tree_write()
820
 
        self.add_cleanup(work_tree.unlock)
 
802
        work_tree, file_list = WorkingTree.open_containing_paths(
 
803
            names_list, default_directory='.')
 
804
        self.add_cleanup(work_tree.lock_tree_write().unlock)
821
805
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
822
806
 
823
807
    def _run(self, tree, names_list, rel_names, after):
902
886
 
903
887
 
904
888
class cmd_pull(Command):
905
 
    """Turn this branch into a mirror of another branch.
 
889
    __doc__ = """Turn this branch into a mirror of another branch.
906
890
 
907
891
    By default, this command only works on branches that have not diverged.
908
892
    Branches are considered diverged if the destination branch's most recent 
931
915
    takes_options = ['remember', 'overwrite', 'revision',
932
916
        custom_help('verbose',
933
917
            help='Show logs of pulled revisions.'),
934
 
        Option('directory',
 
918
        custom_help('directory',
935
919
            help='Branch to pull into, '
936
 
                 'rather than the one containing the working directory.',
937
 
            short_name='d',
938
 
            type=unicode,
939
 
            ),
 
920
                 'rather than the one containing the working directory.'),
940
921
        Option('local',
941
922
            help="Perform a local pull in a bound "
942
923
                 "branch.  Local pulls are not applied to "
957
938
        try:
958
939
            tree_to = WorkingTree.open_containing(directory)[0]
959
940
            branch_to = tree_to.branch
 
941
            self.add_cleanup(tree_to.lock_write().unlock)
960
942
        except errors.NoWorkingTree:
961
943
            tree_to = None
962
944
            branch_to = Branch.open_containing(directory)[0]
963
 
        
 
945
            self.add_cleanup(branch_to.lock_write().unlock)
 
946
 
964
947
        if local and not branch_to.get_bound_location():
965
948
            raise errors.LocalRequiresBoundBranch()
966
949
 
996
979
        else:
997
980
            branch_from = Branch.open(location,
998
981
                possible_transports=possible_transports)
 
982
            self.add_cleanup(branch_from.lock_read().unlock)
999
983
 
1000
984
            if branch_to.get_parent() is None or remember:
1001
985
                branch_to.set_parent(branch_from.base)
1002
986
 
1003
 
        if branch_from is not branch_to:
1004
 
            branch_from.lock_read()
1005
 
            self.add_cleanup(branch_from.unlock)
1006
987
        if revision is not None:
1007
988
            revision_id = revision.as_revision_id(branch_from)
1008
989
 
1009
 
        branch_to.lock_write()
1010
 
        self.add_cleanup(branch_to.unlock)
1011
990
        if tree_to is not None:
1012
991
            view_info = _get_view_info_for_change_reporter(tree_to)
1013
992
            change_reporter = delta._ChangeReporter(
1028
1007
 
1029
1008
 
1030
1009
class cmd_push(Command):
1031
 
    """Update a mirror of this branch.
 
1010
    __doc__ = """Update a mirror of this branch.
1032
1011
 
1033
1012
    The target branch will not have its working tree populated because this
1034
1013
    is both expensive, and is not supported on remote file systems.
1058
1037
        Option('create-prefix',
1059
1038
               help='Create the path leading up to the branch '
1060
1039
                    'if it does not already exist.'),
1061
 
        Option('directory',
 
1040
        custom_help('directory',
1062
1041
            help='Branch to push from, '
1063
 
                 'rather than the one containing the working directory.',
1064
 
            short_name='d',
1065
 
            type=unicode,
1066
 
            ),
 
1042
                 'rather than the one containing the working directory.'),
1067
1043
        Option('use-existing-dir',
1068
1044
               help='By default push will fail if the target'
1069
1045
                    ' directory exists, but does not already'
1095
1071
        # Get the source branch
1096
1072
        (tree, br_from,
1097
1073
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1098
 
        if strict is None:
1099
 
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
1100
 
        if strict is None: strict = True # default value
1101
1074
        # Get the tip's revision_id
1102
1075
        revision = _get_one_revision('push', revision)
1103
1076
        if revision is not None:
1104
1077
            revision_id = revision.in_history(br_from).rev_id
1105
1078
        else:
1106
1079
            revision_id = None
1107
 
        if strict and tree is not None and revision_id is None:
1108
 
            if (tree.has_changes()):
1109
 
                raise errors.UncommittedChanges(
1110
 
                    tree, more='Use --no-strict to force the push.')
1111
 
            if tree.last_revision() != tree.branch.last_revision():
1112
 
                # The tree has lost sync with its branch, there is little
1113
 
                # chance that the user is aware of it but he can still force
1114
 
                # the push with --no-strict
1115
 
                raise errors.OutOfDateTree(
1116
 
                    tree, more='Use --no-strict to force the push.')
1117
 
 
 
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.')
1118
1085
        # Get the stacked_on branch, if any
1119
1086
        if stacked_on is not None:
1120
1087
            stacked_on = urlutils.normalize_url(stacked_on)
1152
1119
 
1153
1120
 
1154
1121
class cmd_branch(Command):
1155
 
    """Create a new branch that is a copy of an existing branch.
 
1122
    __doc__ = """Create a new branch that is a copy of an existing branch.
1156
1123
 
1157
1124
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1158
1125
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1167
1134
 
1168
1135
    _see_also = ['checkout']
1169
1136
    takes_args = ['from_location', 'to_location?']
1170
 
    takes_options = ['revision', Option('hardlink',
1171
 
        help='Hard-link working tree files where possible.'),
 
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."),
1172
1141
        Option('no-tree',
1173
1142
            help="Create a branch without a working-tree."),
1174
1143
        Option('switch',
1192
1161
 
1193
1162
    def run(self, from_location, to_location=None, revision=None,
1194
1163
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1195
 
            use_existing_dir=False, switch=False, bind=False):
 
1164
            use_existing_dir=False, switch=False, bind=False,
 
1165
            files_from=None):
1196
1166
        from bzrlib import switch as _mod_switch
1197
1167
        from bzrlib.tag import _merge_tags_if_possible
1198
1168
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1199
1169
            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
 
1174
            accelerator_tree = None
 
1175
        if files_from is not None and files_from != from_location:
 
1176
            accelerator_tree = WorkingTree.open(files_from)
1200
1177
        revision = _get_one_revision('branch', revision)
1201
 
        br_from.lock_read()
1202
 
        self.add_cleanup(br_from.unlock)
 
1178
        self.add_cleanup(br_from.lock_read().unlock)
1203
1179
        if revision is not None:
1204
1180
            revision_id = revision.as_revision_id(br_from)
1205
1181
        else:
1265
1241
 
1266
1242
 
1267
1243
class cmd_checkout(Command):
1268
 
    """Create a new checkout of an existing branch.
 
1244
    __doc__ = """Create a new checkout of an existing branch.
1269
1245
 
1270
1246
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1271
1247
    the branch found in '.'. This is useful if you have removed the working tree
1310
1286
            to_location = branch_location
1311
1287
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1312
1288
            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
1313
1294
        revision = _get_one_revision('checkout', revision)
1314
 
        if files_from is not None:
 
1295
        if files_from is not None and files_from != branch_location:
1315
1296
            accelerator_tree = WorkingTree.open(files_from)
1316
1297
        if revision is not None:
1317
1298
            revision_id = revision.as_revision_id(source)
1334
1315
 
1335
1316
 
1336
1317
class cmd_renames(Command):
1337
 
    """Show list of renamed files.
 
1318
    __doc__ = """Show list of renamed files.
1338
1319
    """
1339
1320
    # TODO: Option to show renames between two historical versions.
1340
1321
 
1345
1326
    @display_command
1346
1327
    def run(self, dir=u'.'):
1347
1328
        tree = WorkingTree.open_containing(dir)[0]
1348
 
        tree.lock_read()
1349
 
        self.add_cleanup(tree.unlock)
 
1329
        self.add_cleanup(tree.lock_read().unlock)
1350
1330
        new_inv = tree.inventory
1351
1331
        old_tree = tree.basis_tree()
1352
 
        old_tree.lock_read()
1353
 
        self.add_cleanup(old_tree.unlock)
 
1332
        self.add_cleanup(old_tree.lock_read().unlock)
1354
1333
        old_inv = old_tree.inventory
1355
1334
        renames = []
1356
1335
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1366
1345
 
1367
1346
 
1368
1347
class cmd_update(Command):
1369
 
    """Update a tree to have the latest code committed to its branch.
 
1348
    __doc__ = """Update a tree to have the latest code committed to its branch.
1370
1349
 
1371
1350
    This will perform a merge into the working tree, and may generate
1372
1351
    conflicts. If you have any local changes, you will still
1394
1373
        master = branch.get_master_branch(
1395
1374
            possible_transports=possible_transports)
1396
1375
        if master is not None:
1397
 
            tree.lock_write()
1398
1376
            branch_location = master.base
 
1377
            tree.lock_write()
1399
1378
        else:
 
1379
            branch_location = tree.branch.base
1400
1380
            tree.lock_tree_write()
1401
 
            branch_location = tree.branch.base
1402
1381
        self.add_cleanup(tree.unlock)
1403
1382
        # get rid of the final '/' and be ready for display
1404
 
        branch_location = urlutils.unescape_for_display(branch_location[:-1],
1405
 
                                                        self.outf.encoding)
 
1383
        branch_location = urlutils.unescape_for_display(
 
1384
            branch_location.rstrip('/'),
 
1385
            self.outf.encoding)
1406
1386
        existing_pending_merges = tree.get_parent_ids()[1:]
1407
1387
        if master is None:
1408
1388
            old_tip = None
1416
1396
        else:
1417
1397
            revision_id = branch.last_revision()
1418
1398
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1419
 
            revno = branch.revision_id_to_revno(revision_id)
1420
 
            note("Tree is up to date at revision %d of branch %s" %
1421
 
                (revno, branch_location))
 
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))
1422
1402
            return 0
1423
1403
        view_info = _get_view_info_for_change_reporter(tree)
1424
1404
        change_reporter = delta._ChangeReporter(
1436
1416
                                  "bzr update --revision only works"
1437
1417
                                  " for a revision in the branch history"
1438
1418
                                  % (e.revision))
1439
 
        revno = tree.branch.revision_id_to_revno(
 
1419
        revno = tree.branch.revision_id_to_dotted_revno(
1440
1420
            _mod_revision.ensure_null(tree.last_revision()))
1441
 
        note('Updated to revision %d of branch %s' %
1442
 
             (revno, branch_location))
1443
 
        if tree.get_parent_ids()[1:] != existing_pending_merges:
 
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:
1444
1425
            note('Your local commits will now show as pending merges with '
1445
1426
                 "'bzr status', and can be committed with 'bzr commit'.")
1446
1427
        if conflicts != 0:
1450
1431
 
1451
1432
 
1452
1433
class cmd_info(Command):
1453
 
    """Show information about a working tree, branch or repository.
 
1434
    __doc__ = """Show information about a working tree, branch or repository.
1454
1435
 
1455
1436
    This command will show all known locations and formats associated to the
1456
1437
    tree, branch or repository.
1494
1475
 
1495
1476
 
1496
1477
class cmd_remove(Command):
1497
 
    """Remove files or directories.
 
1478
    __doc__ = """Remove files or directories.
1498
1479
 
1499
 
    This makes bzr stop tracking changes to the specified files. bzr will delete
1500
 
    them if they can easily be recovered using revert. If no options or
1501
 
    parameters are given bzr will scan for files that are being tracked by bzr
1502
 
    but missing in your tree and stop tracking them for you.
 
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.
1503
1485
    """
1504
1486
    takes_args = ['file*']
1505
1487
    takes_options = ['verbose',
1507
1489
        RegistryOption.from_kwargs('file-deletion-strategy',
1508
1490
            'The file deletion mode to be used.',
1509
1491
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1510
 
            safe='Only delete files if they can be'
1511
 
                 ' safely recovered (default).',
 
1492
            safe='Backup changed files (default).',
1512
1493
            keep='Delete from bzr but leave the working copy.',
1513
1494
            force='Delete all the specified files, even if they can not be '
1514
1495
                'recovered and even if they are non-empty directories.')]
1517
1498
 
1518
1499
    def run(self, file_list, verbose=False, new=False,
1519
1500
        file_deletion_strategy='safe'):
1520
 
        tree, file_list = tree_files(file_list)
 
1501
        tree, file_list = WorkingTree.open_containing_paths(file_list)
1521
1502
 
1522
1503
        if file_list is not None:
1523
1504
            file_list = [f for f in file_list]
1524
1505
 
1525
 
        tree.lock_write()
1526
 
        self.add_cleanup(tree.unlock)
 
1506
        self.add_cleanup(tree.lock_write().unlock)
1527
1507
        # Heuristics should probably all move into tree.remove_smart or
1528
1508
        # some such?
1529
1509
        if new:
1548
1528
 
1549
1529
 
1550
1530
class cmd_file_id(Command):
1551
 
    """Print file_id of a particular file or directory.
 
1531
    __doc__ = """Print file_id of a particular file or directory.
1552
1532
 
1553
1533
    The file_id is assigned when the file is first added and remains the
1554
1534
    same through all revisions where the file exists, even when it is
1570
1550
 
1571
1551
 
1572
1552
class cmd_file_path(Command):
1573
 
    """Print path of file_ids to a file or directory.
 
1553
    __doc__ = """Print path of file_ids to a file or directory.
1574
1554
 
1575
1555
    This prints one line for each directory down to the target,
1576
1556
    starting at the branch root.
1592
1572
 
1593
1573
 
1594
1574
class cmd_reconcile(Command):
1595
 
    """Reconcile bzr metadata in a branch.
 
1575
    __doc__ = """Reconcile bzr metadata in a branch.
1596
1576
 
1597
1577
    This can correct data mismatches that may have been caused by
1598
1578
    previous ghost operations or bzr upgrades. You should only
1612
1592
 
1613
1593
    _see_also = ['check']
1614
1594
    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
        ]
1615
1601
 
1616
 
    def run(self, branch="."):
 
1602
    def run(self, branch=".", canonicalize_chks=False):
1617
1603
        from bzrlib.reconcile import reconcile
1618
1604
        dir = bzrdir.BzrDir.open(branch)
1619
 
        reconcile(dir)
 
1605
        reconcile(dir, canonicalize_chks=canonicalize_chks)
1620
1606
 
1621
1607
 
1622
1608
class cmd_revision_history(Command):
1623
 
    """Display the list of revision ids on a branch."""
 
1609
    __doc__ = """Display the list of revision ids on a branch."""
1624
1610
 
1625
1611
    _see_also = ['log']
1626
1612
    takes_args = ['location?']
1636
1622
 
1637
1623
 
1638
1624
class cmd_ancestry(Command):
1639
 
    """List all revisions merged into this branch."""
 
1625
    __doc__ = """List all revisions merged into this branch."""
1640
1626
 
1641
1627
    _see_also = ['log', 'revision-history']
1642
1628
    takes_args = ['location?']
1661
1647
 
1662
1648
 
1663
1649
class cmd_init(Command):
1664
 
    """Make a directory into a versioned branch.
 
1650
    __doc__ = """Make a directory into a versioned branch.
1665
1651
 
1666
1652
    Use this to create an empty branch, or before importing an
1667
1653
    existing project.
1770
1756
 
1771
1757
 
1772
1758
class cmd_init_repository(Command):
1773
 
    """Create a shared repository for branches to share storage space.
 
1759
    __doc__ = """Create a shared repository for branches to share storage space.
1774
1760
 
1775
1761
    New branches created under the repository directory will store their
1776
1762
    revisions in the repository, not in the branch directory.  For branches
1830
1816
 
1831
1817
 
1832
1818
class cmd_diff(Command):
1833
 
    """Show differences in the working tree, between revisions or branches.
 
1819
    __doc__ = """Show differences in the working tree, between revisions or branches.
1834
1820
 
1835
1821
    If no arguments are given, all changes for the current tree are listed.
1836
1822
    If files are given, only the changes in those files are listed.
1898
1884
        Same as 'bzr diff' but prefix paths with old/ and new/::
1899
1885
 
1900
1886
            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
1901
1891
    """
1902
1892
    _see_also = ['status']
1903
1893
    takes_args = ['file*']
1922
1912
            help='Use this command to compare files.',
1923
1913
            type=unicode,
1924
1914
            ),
 
1915
        RegistryOption('format',
 
1916
            help='Diff format to use.',
 
1917
            lazy_registry=('bzrlib.diff', 'format_registry'),
 
1918
            value_switches=False, title='Diff format'),
1925
1919
        ]
1926
1920
    aliases = ['di', 'dif']
1927
1921
    encoding_type = 'exact'
1928
1922
 
1929
1923
    @display_command
1930
1924
    def run(self, revision=None, file_list=None, diff_options=None,
1931
 
            prefix=None, old=None, new=None, using=None):
1932
 
        from bzrlib.diff import get_trees_and_branches_to_diff, show_diff_trees
 
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)
1933
1928
 
1934
1929
        if (prefix is None) or (prefix == '0'):
1935
1930
            # diff -p0 format
1949
1944
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1950
1945
                                         ' one or two revision specifiers')
1951
1946
 
 
1947
        if using is not None and format is not None:
 
1948
            raise errors.BzrCommandError('--using and --format are mutually '
 
1949
                'exclusive.')
 
1950
 
1952
1951
        (old_tree, new_tree,
1953
1952
         old_branch, new_branch,
1954
 
         specific_files, extra_trees) = get_trees_and_branches_to_diff(
1955
 
            file_list, revision, old, new, apply_view=True)
 
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()
1956
1957
        return show_diff_trees(old_tree, new_tree, sys.stdout,
1957
1958
                               specific_files=specific_files,
1958
1959
                               external_diff_options=diff_options,
1959
1960
                               old_label=old_label, new_label=new_label,
1960
 
                               extra_trees=extra_trees, using=using)
 
1961
                               extra_trees=extra_trees,
 
1962
                               path_encoding=path_encoding,
 
1963
                               using=using,
 
1964
                               format_cls=format)
1961
1965
 
1962
1966
 
1963
1967
class cmd_deleted(Command):
1964
 
    """List files deleted in the working tree.
 
1968
    __doc__ = """List files deleted in the working tree.
1965
1969
    """
1966
1970
    # TODO: Show files deleted since a previous revision, or
1967
1971
    # between two revisions.
1970
1974
    # level of effort but possibly much less IO.  (Or possibly not,
1971
1975
    # if the directories are very large...)
1972
1976
    _see_also = ['status', 'ls']
1973
 
    takes_options = ['show-ids']
 
1977
    takes_options = ['directory', 'show-ids']
1974
1978
 
1975
1979
    @display_command
1976
 
    def run(self, show_ids=False):
1977
 
        tree = WorkingTree.open_containing(u'.')[0]
1978
 
        tree.lock_read()
1979
 
        self.add_cleanup(tree.unlock)
 
1980
    def run(self, show_ids=False, directory=u'.'):
 
1981
        tree = WorkingTree.open_containing(directory)[0]
 
1982
        self.add_cleanup(tree.lock_read().unlock)
1980
1983
        old = tree.basis_tree()
1981
 
        old.lock_read()
1982
 
        self.add_cleanup(old.unlock)
 
1984
        self.add_cleanup(old.lock_read().unlock)
1983
1985
        for path, ie in old.inventory.iter_entries():
1984
1986
            if not tree.has_id(ie.file_id):
1985
1987
                self.outf.write(path)
1990
1992
 
1991
1993
 
1992
1994
class cmd_modified(Command):
1993
 
    """List files modified in working tree.
 
1995
    __doc__ = """List files modified in working tree.
1994
1996
    """
1995
1997
 
1996
1998
    hidden = True
1997
1999
    _see_also = ['status', 'ls']
1998
 
    takes_options = [
1999
 
            Option('null',
2000
 
                   help='Write an ascii NUL (\\0) separator '
2001
 
                   'between files rather than a newline.')
2002
 
            ]
 
2000
    takes_options = ['directory', 'null']
2003
2001
 
2004
2002
    @display_command
2005
 
    def run(self, null=False):
2006
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2003
    def run(self, null=False, directory=u'.'):
 
2004
        tree = WorkingTree.open_containing(directory)[0]
2007
2005
        td = tree.changes_from(tree.basis_tree())
2008
2006
        for path, id, kind, text_modified, meta_modified in td.modified:
2009
2007
            if null:
2013
2011
 
2014
2012
 
2015
2013
class cmd_added(Command):
2016
 
    """List files added in working tree.
 
2014
    __doc__ = """List files added in working tree.
2017
2015
    """
2018
2016
 
2019
2017
    hidden = True
2020
2018
    _see_also = ['status', 'ls']
2021
 
    takes_options = [
2022
 
            Option('null',
2023
 
                   help='Write an ascii NUL (\\0) separator '
2024
 
                   'between files rather than a newline.')
2025
 
            ]
 
2019
    takes_options = ['directory', 'null']
2026
2020
 
2027
2021
    @display_command
2028
 
    def run(self, null=False):
2029
 
        wt = WorkingTree.open_containing(u'.')[0]
2030
 
        wt.lock_read()
2031
 
        self.add_cleanup(wt.unlock)
 
2022
    def run(self, null=False, directory=u'.'):
 
2023
        wt = WorkingTree.open_containing(directory)[0]
 
2024
        self.add_cleanup(wt.lock_read().unlock)
2032
2025
        basis = wt.basis_tree()
2033
 
        basis.lock_read()
2034
 
        self.add_cleanup(basis.unlock)
 
2026
        self.add_cleanup(basis.lock_read().unlock)
2035
2027
        basis_inv = basis.inventory
2036
2028
        inv = wt.inventory
2037
2029
        for file_id in inv:
2040
2032
            if inv.is_root(file_id) and len(basis_inv) == 0:
2041
2033
                continue
2042
2034
            path = inv.id2path(file_id)
2043
 
            if not os.access(osutils.abspath(path), os.F_OK):
 
2035
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2044
2036
                continue
2045
2037
            if null:
2046
2038
                self.outf.write(path + '\0')
2049
2041
 
2050
2042
 
2051
2043
class cmd_root(Command):
2052
 
    """Show the tree root directory.
 
2044
    __doc__ = """Show the tree root directory.
2053
2045
 
2054
2046
    The root is the nearest enclosing directory with a .bzr control
2055
2047
    directory."""
2079
2071
 
2080
2072
 
2081
2073
class cmd_log(Command):
2082
 
    """Show historical log for a branch or subset of a branch.
 
2074
    __doc__ = """Show historical log for a branch or subset of a branch.
2083
2075
 
2084
2076
    log is bzr's default tool for exploring the history of a branch.
2085
2077
    The branch to use is taken from the first parameter. If no parameters
2246
2238
                   help='Show just the specified revision.'
2247
2239
                   ' See also "help revisionspec".'),
2248
2240
            '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
            ),
2249
2246
            Option('levels',
2250
2247
                   short_name='n',
2251
2248
                   help='Number of levels to display - 0 for all, 1 for flat.',
2266
2263
                   help='Show changes made in each revision as a patch.'),
2267
2264
            Option('include-merges',
2268
2265
                   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
                   )
2269
2270
            ]
2270
2271
    encoding_type = 'replace'
2271
2272
 
2281
2282
            message=None,
2282
2283
            limit=None,
2283
2284
            show_diff=False,
2284
 
            include_merges=False):
 
2285
            include_merges=False,
 
2286
            authors=None,
 
2287
            exclude_common_ancestry=False,
 
2288
            ):
2285
2289
        from bzrlib.log import (
2286
2290
            Logger,
2287
2291
            make_log_request_dict,
2288
2292
            _get_info_for_log_files,
2289
2293
            )
2290
2294
        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')
2291
2299
        if include_merges:
2292
2300
            if levels is None:
2293
2301
                levels = 0
2309
2317
        if file_list:
2310
2318
            # find the file ids to log and check for directory filtering
2311
2319
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2312
 
                revision, file_list)
2313
 
            self.add_cleanup(b.unlock)
 
2320
                revision, file_list, self.add_cleanup)
2314
2321
            for relpath, file_id, kind in file_info_list:
2315
2322
                if file_id is None:
2316
2323
                    raise errors.BzrCommandError(
2334
2341
                location = '.'
2335
2342
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2336
2343
            b = dir.open_branch()
2337
 
            b.lock_read()
2338
 
            self.add_cleanup(b.unlock)
 
2344
            self.add_cleanup(b.lock_read().unlock)
2339
2345
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2340
2346
 
2341
2347
        # Decide on the type of delta & diff filtering to use
2361
2367
                        show_timezone=timezone,
2362
2368
                        delta_format=get_verbosity_level(),
2363
2369
                        levels=levels,
2364
 
                        show_advice=levels is None)
 
2370
                        show_advice=levels is None,
 
2371
                        author_list_handler=authors)
2365
2372
 
2366
2373
        # Choose the algorithm for doing the logging. It's annoying
2367
2374
        # having multiple code paths like this but necessary until
2386
2393
            direction=direction, specific_fileids=file_ids,
2387
2394
            start_revision=rev1, end_revision=rev2, limit=limit,
2388
2395
            message_search=message, delta_type=delta_type,
2389
 
            diff_type=diff_type, _match_using_deltas=match_using_deltas)
 
2396
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
 
2397
            exclude_common_ancestry=exclude_common_ancestry,
 
2398
            )
2390
2399
        Logger(b, rqst).show(lf)
2391
2400
 
2392
2401
 
2411
2420
            raise errors.BzrCommandError(
2412
2421
                "bzr %s doesn't accept two revisions in different"
2413
2422
                " branches." % command_name)
2414
 
        rev1 = start_spec.in_history(branch)
 
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)
2415
2428
        # Avoid loading all of history when we know a missing
2416
2429
        # end of range means the last revision ...
2417
2430
        if end_spec.spec is None:
2446
2459
 
2447
2460
 
2448
2461
class cmd_touching_revisions(Command):
2449
 
    """Return revision-ids which affected a particular file.
 
2462
    __doc__ = """Return revision-ids which affected a particular file.
2450
2463
 
2451
2464
    A more user-friendly interface is "bzr log FILE".
2452
2465
    """
2459
2472
        tree, relpath = WorkingTree.open_containing(filename)
2460
2473
        file_id = tree.path2id(relpath)
2461
2474
        b = tree.branch
2462
 
        b.lock_read()
2463
 
        self.add_cleanup(b.unlock)
 
2475
        self.add_cleanup(b.lock_read().unlock)
2464
2476
        touching_revs = log.find_touching_revisions(b, file_id)
2465
2477
        for revno, revision_id, what in touching_revs:
2466
2478
            self.outf.write("%6d %s\n" % (revno, what))
2467
2479
 
2468
2480
 
2469
2481
class cmd_ls(Command):
2470
 
    """List files in a tree.
 
2482
    __doc__ = """List files in a tree.
2471
2483
    """
2472
2484
 
2473
2485
    _see_also = ['status', 'cat']
2479
2491
                   help='Recurse into subdirectories.'),
2480
2492
            Option('from-root',
2481
2493
                   help='Print paths relative to the root of the branch.'),
2482
 
            Option('unknown', help='Print unknown files.'),
 
2494
            Option('unknown', short_name='u',
 
2495
                help='Print unknown files.'),
2483
2496
            Option('versioned', help='Print versioned files.',
2484
2497
                   short_name='V'),
2485
 
            Option('ignored', help='Print ignored files.'),
2486
 
            Option('null',
2487
 
                   help='Write an ascii NUL (\\0) separator '
2488
 
                   'between files rather than a newline.'),
2489
 
            Option('kind',
 
2498
            Option('ignored', short_name='i',
 
2499
                help='Print ignored files.'),
 
2500
            Option('kind', short_name='k',
2490
2501
                   help='List entries of a particular kind: file, directory, symlink.',
2491
2502
                   type=unicode),
 
2503
            'null',
2492
2504
            'show-ids',
 
2505
            'directory',
2493
2506
            ]
2494
2507
    @display_command
2495
2508
    def run(self, revision=None, verbose=False,
2496
2509
            recursive=False, from_root=False,
2497
2510
            unknown=False, versioned=False, ignored=False,
2498
 
            null=False, kind=None, show_ids=False, path=None):
 
2511
            null=False, kind=None, show_ids=False, path=None, directory=None):
2499
2512
 
2500
2513
        if kind and kind not in ('file', 'directory', 'symlink'):
2501
2514
            raise errors.BzrCommandError('invalid kind specified')
2513
2526
                raise errors.BzrCommandError('cannot specify both --from-root'
2514
2527
                                             ' and PATH')
2515
2528
            fs_path = path
2516
 
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2517
 
            fs_path)
 
2529
        tree, branch, relpath = \
 
2530
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
2518
2531
 
2519
2532
        # Calculate the prefix to use
2520
2533
        prefix = None
2535
2548
                view_str = views.view_display_str(view_files)
2536
2549
                note("Ignoring files outside view. View is %s" % view_str)
2537
2550
 
2538
 
        tree.lock_read()
2539
 
        self.add_cleanup(tree.unlock)
 
2551
        self.add_cleanup(tree.lock_read().unlock)
2540
2552
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2541
2553
            from_dir=relpath, recursive=recursive):
2542
2554
            # Apply additional masking
2584
2596
 
2585
2597
 
2586
2598
class cmd_unknowns(Command):
2587
 
    """List unknown files.
 
2599
    __doc__ = """List unknown files.
2588
2600
    """
2589
2601
 
2590
2602
    hidden = True
2591
2603
    _see_also = ['ls']
 
2604
    takes_options = ['directory']
2592
2605
 
2593
2606
    @display_command
2594
 
    def run(self):
2595
 
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
2607
    def run(self, directory=u'.'):
 
2608
        for f in WorkingTree.open_containing(directory)[0].unknowns():
2596
2609
            self.outf.write(osutils.quotefn(f) + '\n')
2597
2610
 
2598
2611
 
2599
2612
class cmd_ignore(Command):
2600
 
    """Ignore specified files or patterns.
 
2613
    __doc__ = """Ignore specified files or patterns.
2601
2614
 
2602
2615
    See ``bzr help patterns`` for details on the syntax of patterns.
2603
2616
 
2612
2625
    using this command or directly by using an editor, be sure to commit
2613
2626
    it.
2614
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
 
2615
2634
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2616
2635
    precedence over regular ignores.  Such exceptions are used to specify
2617
2636
    files that should be versioned which would otherwise be ignored.
2657
2676
 
2658
2677
    _see_also = ['status', 'ignored', 'patterns']
2659
2678
    takes_args = ['name_pattern*']
2660
 
    takes_options = [
2661
 
        Option('old-default-rules',
2662
 
               help='Write out the ignore rules bzr < 0.9 always used.')
 
2679
    takes_options = ['directory',
 
2680
        Option('default-rules',
 
2681
               help='Display the default ignore rules that bzr uses.')
2663
2682
        ]
2664
2683
 
2665
 
    def run(self, name_pattern_list=None, old_default_rules=None):
 
2684
    def run(self, name_pattern_list=None, default_rules=None,
 
2685
            directory=u'.'):
2666
2686
        from bzrlib import ignores
2667
 
        if old_default_rules is not None:
2668
 
            # dump the rules and exit
2669
 
            for pattern in ignores.OLD_DEFAULTS:
2670
 
                print pattern
 
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)
2671
2691
            return
2672
2692
        if not name_pattern_list:
2673
2693
            raise errors.BzrCommandError("ignore requires at least one "
2674
 
                                  "NAME_PATTERN or --old-default-rules")
 
2694
                "NAME_PATTERN or --default-rules.")
2675
2695
        name_pattern_list = [globbing.normalize_pattern(p)
2676
2696
                             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('')
2677
2705
        for name_pattern in name_pattern_list:
2678
2706
            if (name_pattern[0] == '/' or
2679
2707
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2680
2708
                raise errors.BzrCommandError(
2681
2709
                    "NAME_PATTERN should not be an absolute path")
2682
 
        tree, relpath = WorkingTree.open_containing(u'.')
 
2710
        tree, relpath = WorkingTree.open_containing(directory)
2683
2711
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2684
2712
        ignored = globbing.Globster(name_pattern_list)
2685
2713
        matches = []
2686
 
        tree.lock_read()
 
2714
        self.add_cleanup(tree.lock_read().unlock)
2687
2715
        for entry in tree.list_files():
2688
2716
            id = entry[3]
2689
2717
            if id is not None:
2690
2718
                filename = entry[0]
2691
2719
                if ignored.match(filename):
2692
 
                    matches.append(filename.encode('utf-8'))
2693
 
        tree.unlock()
 
2720
                    matches.append(filename)
2694
2721
        if len(matches) > 0:
2695
 
            print "Warning: the following files are version controlled and" \
2696
 
                  " match your ignore pattern:\n%s" \
2697
 
                  "\nThese files will continue to be version controlled" \
2698
 
                  " unless you 'bzr remove' them." % ("\n".join(matches),)
 
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),))
2699
2726
 
2700
2727
 
2701
2728
class cmd_ignored(Command):
2702
 
    """List ignored files and the patterns that matched them.
 
2729
    __doc__ = """List ignored files and the patterns that matched them.
2703
2730
 
2704
2731
    List all the ignored files and the ignore pattern that caused the file to
2705
2732
    be ignored.
2711
2738
 
2712
2739
    encoding_type = 'replace'
2713
2740
    _see_also = ['ignore', 'ls']
 
2741
    takes_options = ['directory']
2714
2742
 
2715
2743
    @display_command
2716
 
    def run(self):
2717
 
        tree = WorkingTree.open_containing(u'.')[0]
2718
 
        tree.lock_read()
2719
 
        self.add_cleanup(tree.unlock)
 
2744
    def run(self, directory=u'.'):
 
2745
        tree = WorkingTree.open_containing(directory)[0]
 
2746
        self.add_cleanup(tree.lock_read().unlock)
2720
2747
        for path, file_class, kind, file_id, entry in tree.list_files():
2721
2748
            if file_class != 'I':
2722
2749
                continue
2726
2753
 
2727
2754
 
2728
2755
class cmd_lookup_revision(Command):
2729
 
    """Lookup the revision-id from a revision-number
 
2756
    __doc__ = """Lookup the revision-id from a revision-number
2730
2757
 
2731
2758
    :Examples:
2732
2759
        bzr lookup-revision 33
2733
2760
    """
2734
2761
    hidden = True
2735
2762
    takes_args = ['revno']
 
2763
    takes_options = ['directory']
2736
2764
 
2737
2765
    @display_command
2738
 
    def run(self, revno):
 
2766
    def run(self, revno, directory=u'.'):
2739
2767
        try:
2740
2768
            revno = int(revno)
2741
2769
        except ValueError:
2742
 
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2743
 
 
2744
 
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
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)
2745
2774
 
2746
2775
 
2747
2776
class cmd_export(Command):
2748
 
    """Export current or past revision to a destination directory or archive.
 
2777
    __doc__ = """Export current or past revision to a destination directory or archive.
2749
2778
 
2750
2779
    If no revision is specified this exports the last committed revision.
2751
2780
 
2773
2802
      =================       =========================
2774
2803
    """
2775
2804
    takes_args = ['dest', 'branch_or_subdir?']
2776
 
    takes_options = [
 
2805
    takes_options = ['directory',
2777
2806
        Option('format',
2778
2807
               help="Type of file to export to.",
2779
2808
               type=unicode),
2783
2812
        Option('root',
2784
2813
               type=str,
2785
2814
               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.'),
2786
2818
        ]
2787
2819
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2788
 
        root=None, filters=False):
 
2820
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2789
2821
        from bzrlib.export import export
2790
2822
 
2791
2823
        if branch_or_subdir is None:
2792
 
            tree = WorkingTree.open_containing(u'.')[0]
 
2824
            tree = WorkingTree.open_containing(directory)[0]
2793
2825
            b = tree.branch
2794
2826
            subdir = None
2795
2827
        else:
2798
2830
 
2799
2831
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2800
2832
        try:
2801
 
            export(rev_tree, dest, format, root, subdir, filtered=filters)
 
2833
            export(rev_tree, dest, format, root, subdir, filtered=filters,
 
2834
                   per_file_timestamps=per_file_timestamps)
2802
2835
        except errors.NoSuchExportFormat, e:
2803
2836
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2804
2837
 
2805
2838
 
2806
2839
class cmd_cat(Command):
2807
 
    """Write the contents of a file as of a given revision to standard output.
 
2840
    __doc__ = """Write the contents of a file as of a given revision to standard output.
2808
2841
 
2809
2842
    If no revision is nominated, the last revision is used.
2810
2843
 
2813
2846
    """
2814
2847
 
2815
2848
    _see_also = ['ls']
2816
 
    takes_options = [
 
2849
    takes_options = ['directory',
2817
2850
        Option('name-from-revision', help='The path name in the old tree.'),
2818
2851
        Option('filters', help='Apply content filters to display the '
2819
2852
                'convenience form.'),
2824
2857
 
2825
2858
    @display_command
2826
2859
    def run(self, filename, revision=None, name_from_revision=False,
2827
 
            filters=False):
 
2860
            filters=False, directory=None):
2828
2861
        if revision is not None and len(revision) != 1:
2829
2862
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2830
2863
                                         " one revision specifier")
2831
2864
        tree, branch, relpath = \
2832
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2833
 
        branch.lock_read()
2834
 
        self.add_cleanup(branch.unlock)
 
2865
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
2866
        self.add_cleanup(branch.lock_read().unlock)
2835
2867
        return self._run(tree, branch, relpath, filename, revision,
2836
2868
                         name_from_revision, filters)
2837
2869
 
2840
2872
        if tree is None:
2841
2873
            tree = b.basis_tree()
2842
2874
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2843
 
        rev_tree.lock_read()
2844
 
        self.add_cleanup(rev_tree.unlock)
 
2875
        self.add_cleanup(rev_tree.lock_read().unlock)
2845
2876
 
2846
2877
        old_file_id = rev_tree.path2id(relpath)
2847
2878
 
2890
2921
 
2891
2922
 
2892
2923
class cmd_local_time_offset(Command):
2893
 
    """Show the offset in seconds from GMT to local time."""
 
2924
    __doc__ = """Show the offset in seconds from GMT to local time."""
2894
2925
    hidden = True
2895
2926
    @display_command
2896
2927
    def run(self):
2897
 
        print osutils.local_time_offset()
 
2928
        self.outf.write("%s\n" % osutils.local_time_offset())
2898
2929
 
2899
2930
 
2900
2931
 
2901
2932
class cmd_commit(Command):
2902
 
    """Commit changes into a new revision.
 
2933
    __doc__ = """Commit changes into a new revision.
2903
2934
 
2904
2935
    An explanatory message needs to be given for each commit. This is
2905
2936
    often done by using the --message option (getting the message from the
3013
3044
                         "the master branch until a normal commit "
3014
3045
                         "is performed."
3015
3046
                    ),
3016
 
             Option('show-diff',
 
3047
             Option('show-diff', short_name='p',
3017
3048
                    help='When no message is supplied, show the diff along'
3018
3049
                    ' with the status summary in the message editor.'),
3019
3050
             ]
3068
3099
 
3069
3100
        properties = {}
3070
3101
 
3071
 
        tree, selected_list = tree_files(selected_list)
 
3102
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
3072
3103
        if selected_list == ['']:
3073
3104
            # workaround - commit of root of tree should be exactly the same
3074
3105
            # as just default commit in that tree, and succeed even though
3099
3130
                    '(use --file "%(f)s" to take commit message from that file)'
3100
3131
                    % { 'f': message })
3101
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")
3102
3139
 
3103
3140
        def get_message(commit_obj):
3104
3141
            """Callback to get commit message"""
3105
 
            my_message = message
3106
 
            if my_message is not None and '\r' in my_message:
3107
 
                my_message = my_message.replace('\r\n', '\n')
3108
 
                my_message = my_message.replace('\r', '\n')
3109
 
            if my_message is None and not file:
3110
 
                t = make_commit_message_template_encoded(tree,
 
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,
3111
3154
                        selected_list, diff=show_diff,
3112
3155
                        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.
3113
3161
                start_message = generate_commit_message_template(commit_obj)
3114
 
                my_message = edit_commit_message_encoded(t,
 
3162
                my_message = edit_commit_message_encoded(text,
3115
3163
                    start_message=start_message)
3116
3164
                if my_message is None:
3117
3165
                    raise errors.BzrCommandError("please specify a commit"
3118
3166
                        " message with either --message or --file")
3119
 
            elif my_message and file:
3120
 
                raise errors.BzrCommandError(
3121
 
                    "please specify either --message or --file")
3122
 
            if file:
3123
 
                my_message = codecs.open(file, 'rt',
3124
 
                                         osutils.get_user_encoding()).read()
3125
3167
            if my_message == "":
3126
3168
                raise errors.BzrCommandError("empty commit message specified")
3127
3169
            return my_message
3137
3179
                        reporter=None, verbose=verbose, revprops=properties,
3138
3180
                        authors=author, timestamp=commit_stamp,
3139
3181
                        timezone=offset,
3140
 
                        exclude=safe_relpath_files(tree, exclude))
 
3182
                        exclude=tree.safe_relpath_files(exclude))
3141
3183
        except PointlessCommit:
3142
 
            # FIXME: This should really happen before the file is read in;
3143
 
            # perhaps prepare the commit; get the message; then actually commit
3144
3184
            raise errors.BzrCommandError("No changes to commit."
3145
3185
                              " Use --unchanged to commit anyhow.")
3146
3186
        except ConflictsInTree:
3151
3191
            raise errors.BzrCommandError("Commit refused because there are"
3152
3192
                              " unknown files in the working tree.")
3153
3193
        except errors.BoundBranchOutOfDate, e:
3154
 
            raise errors.BzrCommandError(str(e) + "\n"
3155
 
            'To commit to master branch, run update and then commit.\n'
3156
 
            'You can also pass --local to commit to continue working '
3157
 
            'disconnected.')
 
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
3158
3199
 
3159
3200
 
3160
3201
class cmd_check(Command):
3161
 
    """Validate working tree structure, branch consistency and repository history.
 
3202
    __doc__ = """Validate working tree structure, branch consistency and repository history.
3162
3203
 
3163
3204
    This command checks various invariants about branch and repository storage
3164
3205
    to detect data corruption or bzr bugs.
3228
3269
 
3229
3270
 
3230
3271
class cmd_upgrade(Command):
3231
 
    """Upgrade branch storage to current format.
 
3272
    __doc__ = """Upgrade branch storage to current format.
3232
3273
 
3233
3274
    The check command or bzr developers may sometimes advise you to run
3234
3275
    this command. When the default format has changed you may also be warned
3252
3293
 
3253
3294
 
3254
3295
class cmd_whoami(Command):
3255
 
    """Show or set bzr user id.
 
3296
    __doc__ = """Show or set bzr user id.
3256
3297
 
3257
3298
    :Examples:
3258
3299
        Show the email of the current user::
3263
3304
 
3264
3305
            bzr whoami "Frank Chu <fchu@example.com>"
3265
3306
    """
3266
 
    takes_options = [ Option('email',
 
3307
    takes_options = [ 'directory',
 
3308
                      Option('email',
3267
3309
                             help='Display email address only.'),
3268
3310
                      Option('branch',
3269
3311
                             help='Set identity for the current branch instead of '
3273
3315
    encoding_type = 'replace'
3274
3316
 
3275
3317
    @display_command
3276
 
    def run(self, email=False, branch=False, name=None):
 
3318
    def run(self, email=False, branch=False, name=None, directory=None):
3277
3319
        if name is None:
3278
 
            # use branch if we're inside one; otherwise global config
3279
 
            try:
3280
 
                c = Branch.open_containing('.')[0].get_config()
3281
 
            except errors.NotBranchError:
3282
 
                c = config.GlobalConfig()
 
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 = config.GlobalConfig()
 
3326
            else:
 
3327
                c = Branch.open(directory).get_config()
3283
3328
            if email:
3284
3329
                self.outf.write(c.user_email() + '\n')
3285
3330
            else:
3295
3340
 
3296
3341
        # use global config unless --branch given
3297
3342
        if branch:
3298
 
            c = Branch.open_containing('.')[0].get_config()
 
3343
            if directory is None:
 
3344
                c = Branch.open_containing(u'.')[0].get_config()
 
3345
            else:
 
3346
                c = Branch.open(directory).get_config()
3299
3347
        else:
3300
3348
            c = config.GlobalConfig()
3301
3349
        c.set_user_option('email', name)
3302
3350
 
3303
3351
 
3304
3352
class cmd_nick(Command):
3305
 
    """Print or set the branch nickname.
 
3353
    __doc__ = """Print or set the branch nickname.
3306
3354
 
3307
3355
    If unset, the tree root directory name is used as the nickname.
3308
3356
    To print the current nickname, execute with no argument.
3313
3361
 
3314
3362
    _see_also = ['info']
3315
3363
    takes_args = ['nickname?']
3316
 
    def run(self, nickname=None):
3317
 
        branch = Branch.open_containing(u'.')[0]
 
3364
    takes_options = ['directory']
 
3365
    def run(self, nickname=None, directory=u'.'):
 
3366
        branch = Branch.open_containing(directory)[0]
3318
3367
        if nickname is None:
3319
3368
            self.printme(branch)
3320
3369
        else:
3322
3371
 
3323
3372
    @display_command
3324
3373
    def printme(self, branch):
3325
 
        print branch.nick
 
3374
        self.outf.write('%s\n' % branch.nick)
3326
3375
 
3327
3376
 
3328
3377
class cmd_alias(Command):
3329
 
    """Set/unset and display aliases.
 
3378
    __doc__ = """Set/unset and display aliases.
3330
3379
 
3331
3380
    :Examples:
3332
3381
        Show the current aliases::
3396
3445
 
3397
3446
 
3398
3447
class cmd_selftest(Command):
3399
 
    """Run internal test suite.
 
3448
    __doc__ = """Run internal test suite.
3400
3449
 
3401
3450
    If arguments are given, they are regular expressions that say which tests
3402
3451
    should run.  Tests matching any expression are run, and other tests are
3470
3519
                                 'throughout the test suite.',
3471
3520
                            type=get_transport_type),
3472
3521
                     Option('benchmark',
3473
 
                            help='Run the benchmarks rather than selftests.'),
 
3522
                            help='Run the benchmarks rather than selftests.',
 
3523
                            hidden=True),
3474
3524
                     Option('lsprof-timed',
3475
3525
                            help='Generate lsprof output for benchmarked'
3476
3526
                                 ' sections of code.'),
3477
3527
                     Option('lsprof-tests',
3478
3528
                            help='Generate lsprof output for each test.'),
3479
 
                     Option('cache-dir', type=str,
3480
 
                            help='Cache intermediate benchmark output in this '
3481
 
                                 'directory.'),
3482
3529
                     Option('first',
3483
3530
                            help='Run all tests, but run specified tests first.',
3484
3531
                            short_name='f',
3518
3565
 
3519
3566
    def run(self, testspecs_list=None, verbose=False, one=False,
3520
3567
            transport=None, benchmark=None,
3521
 
            lsprof_timed=None, cache_dir=None,
 
3568
            lsprof_timed=None,
3522
3569
            first=False, list_only=False,
3523
3570
            randomize=None, exclude=None, strict=False,
3524
3571
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3525
3572
            parallel=None, lsprof_tests=False):
3526
3573
        from bzrlib.tests import selftest
3527
 
        import bzrlib.benchmarks as benchmarks
3528
 
        from bzrlib.benchmarks import tree_creator
3529
3574
 
3530
3575
        # Make deprecation warnings visible, unless -Werror is set
3531
3576
        symbol_versioning.activate_deprecation_warnings(override=False)
3532
3577
 
3533
 
        if cache_dir is not None:
3534
 
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3535
3578
        if testspecs_list is not None:
3536
3579
            pattern = '|'.join(testspecs_list)
3537
3580
        else:
3543
3586
                raise errors.BzrCommandError("subunit not available. subunit "
3544
3587
                    "needs to be installed to use --subunit.")
3545
3588
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
 
3589
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
 
3590
            # stdout, which would corrupt the subunit stream. 
 
3591
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
3592
            # following code can be deleted when it's sufficiently deployed
 
3593
            # -- vila/mgz 20100514
 
3594
            if (sys.platform == "win32"
 
3595
                and getattr(sys.stdout, 'fileno', None) is not None):
 
3596
                import msvcrt
 
3597
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3546
3598
        if parallel:
3547
3599
            self.additional_selftest_args.setdefault(
3548
3600
                'suite_decorators', []).append(parallel)
3549
3601
        if benchmark:
3550
 
            test_suite_factory = benchmarks.test_suite
3551
 
            # Unless user explicitly asks for quiet, be verbose in benchmarks
3552
 
            verbose = not is_quiet()
3553
 
            # TODO: should possibly lock the history file...
3554
 
            benchfile = open(".perf_history", "at", buffering=1)
3555
 
            self.add_cleanup(benchfile.close)
3556
 
        else:
3557
 
            test_suite_factory = None
3558
 
            benchfile = None
 
3602
            raise errors.BzrCommandError(
 
3603
                "--benchmark is no longer supported from bzr 2.2; "
 
3604
                "use bzr-usertest instead")
 
3605
        test_suite_factory = None
3559
3606
        selftest_kwargs = {"verbose": verbose,
3560
3607
                          "pattern": pattern,
3561
3608
                          "stop_on_failure": one,
3563
3610
                          "test_suite_factory": test_suite_factory,
3564
3611
                          "lsprof_timed": lsprof_timed,
3565
3612
                          "lsprof_tests": lsprof_tests,
3566
 
                          "bench_history": benchfile,
3567
3613
                          "matching_tests_first": first,
3568
3614
                          "list_only": list_only,
3569
3615
                          "random_seed": randomize,
3579
3625
 
3580
3626
 
3581
3627
class cmd_version(Command):
3582
 
    """Show version of bzr."""
 
3628
    __doc__ = """Show version of bzr."""
3583
3629
 
3584
3630
    encoding_type = 'replace'
3585
3631
    takes_options = [
3596
3642
 
3597
3643
 
3598
3644
class cmd_rocks(Command):
3599
 
    """Statement of optimism."""
 
3645
    __doc__ = """Statement of optimism."""
3600
3646
 
3601
3647
    hidden = True
3602
3648
 
3603
3649
    @display_command
3604
3650
    def run(self):
3605
 
        print "It sure does!"
 
3651
        self.outf.write("It sure does!\n")
3606
3652
 
3607
3653
 
3608
3654
class cmd_find_merge_base(Command):
3609
 
    """Find and print a base revision for merging two branches."""
 
3655
    __doc__ = """Find and print a base revision for merging two branches."""
3610
3656
    # TODO: Options to specify revisions on either side, as if
3611
3657
    #       merging only part of the history.
3612
3658
    takes_args = ['branch', 'other']
3618
3664
 
3619
3665
        branch1 = Branch.open_containing(branch)[0]
3620
3666
        branch2 = Branch.open_containing(other)[0]
3621
 
        branch1.lock_read()
3622
 
        self.add_cleanup(branch1.unlock)
3623
 
        branch2.lock_read()
3624
 
        self.add_cleanup(branch2.unlock)
 
3667
        self.add_cleanup(branch1.lock_read().unlock)
 
3668
        self.add_cleanup(branch2.lock_read().unlock)
3625
3669
        last1 = ensure_null(branch1.last_revision())
3626
3670
        last2 = ensure_null(branch2.last_revision())
3627
3671
 
3628
3672
        graph = branch1.repository.get_graph(branch2.repository)
3629
3673
        base_rev_id = graph.find_unique_lca(last1, last2)
3630
3674
 
3631
 
        print 'merge base is revision %s' % base_rev_id
 
3675
        self.outf.write('merge base is revision %s\n' % base_rev_id)
3632
3676
 
3633
3677
 
3634
3678
class cmd_merge(Command):
3635
 
    """Perform a three-way merge.
 
3679
    __doc__ = """Perform a three-way merge.
3636
3680
 
3637
3681
    The source of the merge can be specified either in the form of a branch,
3638
3682
    or in the form of a path to a file containing a merge directive generated
3721
3765
                ' completely merged into the source, pull from the'
3722
3766
                ' source rather than merging.  When this happens,'
3723
3767
                ' you do not need to commit the result.'),
3724
 
        Option('directory',
 
3768
        custom_help('directory',
3725
3769
               help='Branch to merge into, '
3726
 
                    'rather than the one containing the working directory.',
3727
 
               short_name='d',
3728
 
               type=unicode,
3729
 
               ),
 
3770
                    'rather than the one containing the working directory.'),
3730
3771
        Option('preview', help='Instead of merging, show a diff of the'
3731
3772
               ' merge.'),
3732
3773
        Option('interactive', help='Select changes interactively.',
3765
3806
            unversioned_filter=tree.is_ignored, view_info=view_info)
3766
3807
        pb = ui.ui_factory.nested_progress_bar()
3767
3808
        self.add_cleanup(pb.finished)
3768
 
        tree.lock_write()
3769
 
        self.add_cleanup(tree.unlock)
 
3809
        self.add_cleanup(tree.lock_write().unlock)
3770
3810
        if location is not None:
3771
3811
            try:
3772
3812
                mergeable = bundle.read_mergeable_from_url(location,
3833
3873
    def _do_preview(self, merger):
3834
3874
        from bzrlib.diff import show_diff_trees
3835
3875
        result_tree = self._get_preview(merger)
 
3876
        path_encoding = osutils.get_diff_header_encoding()
3836
3877
        show_diff_trees(merger.this_tree, result_tree, self.outf,
3837
 
                        old_label='', new_label='')
 
3878
                        old_label='', new_label='',
 
3879
                        path_encoding=path_encoding)
3838
3880
 
3839
3881
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3840
3882
        merger.change_reporter = change_reporter
3993
4035
 
3994
4036
 
3995
4037
class cmd_remerge(Command):
3996
 
    """Redo a merge.
 
4038
    __doc__ = """Redo a merge.
3997
4039
 
3998
4040
    Use this if you want to try a different merge technique while resolving
3999
4041
    conflicts.  Some merge techniques are better than others, and remerge
4024
4066
 
4025
4067
    def run(self, file_list=None, merge_type=None, show_base=False,
4026
4068
            reprocess=False):
 
4069
        from bzrlib.conflicts import restore
4027
4070
        if merge_type is None:
4028
4071
            merge_type = _mod_merge.Merge3Merger
4029
 
        tree, file_list = tree_files(file_list)
4030
 
        tree.lock_write()
4031
 
        self.add_cleanup(tree.unlock)
 
4072
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
4073
        self.add_cleanup(tree.lock_write().unlock)
4032
4074
        parents = tree.get_parent_ids()
4033
4075
        if len(parents) != 2:
4034
4076
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4087
4129
 
4088
4130
 
4089
4131
class cmd_revert(Command):
4090
 
    """Revert files to a previous revision.
 
4132
    __doc__ = """Revert files to a previous revision.
4091
4133
 
4092
4134
    Giving a list of files will revert only those files.  Otherwise, all files
4093
4135
    will be reverted.  If the revision is not specified with '--revision', the
4143
4185
 
4144
4186
    def run(self, revision=None, no_backup=False, file_list=None,
4145
4187
            forget_merges=None):
4146
 
        tree, file_list = tree_files(file_list)
4147
 
        tree.lock_write()
4148
 
        self.add_cleanup(tree.unlock)
 
4188
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
4189
        self.add_cleanup(tree.lock_tree_write().unlock)
4149
4190
        if forget_merges:
4150
4191
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4151
4192
        else:
4159
4200
 
4160
4201
 
4161
4202
class cmd_assert_fail(Command):
4162
 
    """Test reporting of assertion failures"""
 
4203
    __doc__ = """Test reporting of assertion failures"""
4163
4204
    # intended just for use in testing
4164
4205
 
4165
4206
    hidden = True
4169
4210
 
4170
4211
 
4171
4212
class cmd_help(Command):
4172
 
    """Show help on a command or other topic.
 
4213
    __doc__ = """Show help on a command or other topic.
4173
4214
    """
4174
4215
 
4175
4216
    _see_also = ['topics']
4188
4229
 
4189
4230
 
4190
4231
class cmd_shell_complete(Command):
4191
 
    """Show appropriate completions for context.
 
4232
    __doc__ = """Show appropriate completions for context.
4192
4233
 
4193
4234
    For a list of all available commands, say 'bzr shell-complete'.
4194
4235
    """
4203
4244
 
4204
4245
 
4205
4246
class cmd_missing(Command):
4206
 
    """Show unmerged/unpulled revisions between two branches.
 
4247
    __doc__ = """Show unmerged/unpulled revisions between two branches.
4207
4248
 
4208
4249
    OTHER_BRANCH may be local or remote.
4209
4250
 
4240
4281
    _see_also = ['merge', 'pull']
4241
4282
    takes_args = ['other_branch?']
4242
4283
    takes_options = [
 
4284
        'directory',
4243
4285
        Option('reverse', 'Reverse the order of revisions.'),
4244
4286
        Option('mine-only',
4245
4287
               'Display changes in the local branch only.'),
4267
4309
            theirs_only=False,
4268
4310
            log_format=None, long=False, short=False, line=False,
4269
4311
            show_ids=False, verbose=False, this=False, other=False,
4270
 
            include_merges=False, revision=None, my_revision=None):
 
4312
            include_merges=False, revision=None, my_revision=None,
 
4313
            directory=u'.'):
4271
4314
        from bzrlib.missing import find_unmerged, iter_log_revisions
4272
4315
        def message(s):
4273
4316
            if not is_quiet():
4286
4329
        elif theirs_only:
4287
4330
            restrict = 'remote'
4288
4331
 
4289
 
        local_branch = Branch.open_containing(u".")[0]
 
4332
        local_branch = Branch.open_containing(directory)[0]
 
4333
        self.add_cleanup(local_branch.lock_read().unlock)
 
4334
 
4290
4335
        parent = local_branch.get_parent()
4291
4336
        if other_branch is None:
4292
4337
            other_branch = parent
4301
4346
        remote_branch = Branch.open(other_branch)
4302
4347
        if remote_branch.base == local_branch.base:
4303
4348
            remote_branch = local_branch
 
4349
        else:
 
4350
            self.add_cleanup(remote_branch.lock_read().unlock)
4304
4351
 
4305
 
        local_branch.lock_read()
4306
 
        self.add_cleanup(local_branch.unlock)
4307
4352
        local_revid_range = _revision_range_to_revid_range(
4308
4353
            _get_revision_range(my_revision, local_branch,
4309
4354
                self.name()))
4310
4355
 
4311
 
        remote_branch.lock_read()
4312
 
        self.add_cleanup(remote_branch.unlock)
4313
4356
        remote_revid_range = _revision_range_to_revid_range(
4314
4357
            _get_revision_range(revision,
4315
4358
                remote_branch, self.name()))
4365
4408
            message("Branches are up to date.\n")
4366
4409
        self.cleanup_now()
4367
4410
        if not status_code and parent is None and other_branch is not None:
4368
 
            local_branch.lock_write()
4369
 
            self.add_cleanup(local_branch.unlock)
 
4411
            self.add_cleanup(local_branch.lock_write().unlock)
4370
4412
            # handle race conditions - a parent might be set while we run.
4371
4413
            if local_branch.get_parent() is None:
4372
4414
                local_branch.set_parent(remote_branch.base)
4374
4416
 
4375
4417
 
4376
4418
class cmd_pack(Command):
4377
 
    """Compress the data within a repository."""
 
4419
    __doc__ = """Compress the data within a repository.
 
4420
 
 
4421
    This operation compresses the data within a bazaar repository. As
 
4422
    bazaar supports automatic packing of repository, this operation is
 
4423
    normally not required to be done manually.
 
4424
 
 
4425
    During the pack operation, bazaar takes a backup of existing repository
 
4426
    data, i.e. pack files. This backup is eventually removed by bazaar
 
4427
    automatically when it is safe to do so. To save disk space by removing
 
4428
    the backed up pack files, the --clean-obsolete-packs option may be
 
4429
    used.
 
4430
 
 
4431
    Warning: If you use --clean-obsolete-packs and your machine crashes
 
4432
    during or immediately after repacking, you may be left with a state
 
4433
    where the deletion has been written to disk but the new packs have not
 
4434
    been. In this case the repository may be unusable.
 
4435
    """
4378
4436
 
4379
4437
    _see_also = ['repositories']
4380
4438
    takes_args = ['branch_or_repo?']
 
4439
    takes_options = [
 
4440
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
 
4441
        ]
4381
4442
 
4382
 
    def run(self, branch_or_repo='.'):
 
4443
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4383
4444
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4384
4445
        try:
4385
4446
            branch = dir.open_branch()
4386
4447
            repository = branch.repository
4387
4448
        except errors.NotBranchError:
4388
4449
            repository = dir.open_repository()
4389
 
        repository.pack()
 
4450
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4390
4451
 
4391
4452
 
4392
4453
class cmd_plugins(Command):
4393
 
    """List the installed plugins.
 
4454
    __doc__ = """List the installed plugins.
4394
4455
 
4395
4456
    This command displays the list of installed plugins including
4396
4457
    version of plugin and a short description of each.
4427
4488
                doc = '(no description)'
4428
4489
            result.append((name_ver, doc, plugin.path()))
4429
4490
        for name_ver, doc, path in sorted(result):
4430
 
            print name_ver
4431
 
            print '   ', doc
 
4491
            self.outf.write("%s\n" % name_ver)
 
4492
            self.outf.write("   %s\n" % doc)
4432
4493
            if verbose:
4433
 
                print '   ', path
4434
 
            print
 
4494
                self.outf.write("   %s\n" % path)
 
4495
            self.outf.write("\n")
4435
4496
 
4436
4497
 
4437
4498
class cmd_testament(Command):
4438
 
    """Show testament (signing-form) of a revision."""
 
4499
    __doc__ = """Show testament (signing-form) of a revision."""
4439
4500
    takes_options = [
4440
4501
            'revision',
4441
4502
            Option('long', help='Produce long-format testament.'),
4453
4514
            b = Branch.open_containing(branch)[0]
4454
4515
        else:
4455
4516
            b = Branch.open(branch)
4456
 
        b.lock_read()
4457
 
        self.add_cleanup(b.unlock)
 
4517
        self.add_cleanup(b.lock_read().unlock)
4458
4518
        if revision is None:
4459
4519
            rev_id = b.last_revision()
4460
4520
        else:
4467
4527
 
4468
4528
 
4469
4529
class cmd_annotate(Command):
4470
 
    """Show the origin of each line in a file.
 
4530
    __doc__ = """Show the origin of each line in a file.
4471
4531
 
4472
4532
    This prints out the given file with an annotation on the left side
4473
4533
    indicating which revision, author and date introduced the change.
4484
4544
                     Option('long', help='Show commit date in annotations.'),
4485
4545
                     'revision',
4486
4546
                     'show-ids',
 
4547
                     'directory',
4487
4548
                     ]
4488
4549
    encoding_type = 'exact'
4489
4550
 
4490
4551
    @display_command
4491
4552
    def run(self, filename, all=False, long=False, revision=None,
4492
 
            show_ids=False):
 
4553
            show_ids=False, directory=None):
4493
4554
        from bzrlib.annotate import annotate_file, annotate_file_tree
4494
4555
        wt, branch, relpath = \
4495
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
4556
            _open_directory_or_containing_tree_or_branch(filename, directory)
4496
4557
        if wt is not None:
4497
 
            wt.lock_read()
4498
 
            self.add_cleanup(wt.unlock)
 
4558
            self.add_cleanup(wt.lock_read().unlock)
4499
4559
        else:
4500
 
            branch.lock_read()
4501
 
            self.add_cleanup(branch.unlock)
 
4560
            self.add_cleanup(branch.lock_read().unlock)
4502
4561
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4503
 
        tree.lock_read()
4504
 
        self.add_cleanup(tree.unlock)
 
4562
        self.add_cleanup(tree.lock_read().unlock)
4505
4563
        if wt is not None:
4506
4564
            file_id = wt.path2id(relpath)
4507
4565
        else:
4520
4578
 
4521
4579
 
4522
4580
class cmd_re_sign(Command):
4523
 
    """Create a digital signature for an existing revision."""
 
4581
    __doc__ = """Create a digital signature for an existing revision."""
4524
4582
    # TODO be able to replace existing ones.
4525
4583
 
4526
4584
    hidden = True # is this right ?
4527
4585
    takes_args = ['revision_id*']
4528
 
    takes_options = ['revision']
 
4586
    takes_options = ['directory', 'revision']
4529
4587
 
4530
 
    def run(self, revision_id_list=None, revision=None):
 
4588
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
4531
4589
        if revision_id_list is not None and revision is not None:
4532
4590
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4533
4591
        if revision_id_list is None and revision is None:
4534
4592
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4535
 
        b = WorkingTree.open_containing(u'.')[0].branch
4536
 
        b.lock_write()
4537
 
        self.add_cleanup(b.unlock)
 
4593
        b = WorkingTree.open_containing(directory)[0].branch
 
4594
        self.add_cleanup(b.lock_write().unlock)
4538
4595
        return self._run(b, revision_id_list, revision)
4539
4596
 
4540
4597
    def _run(self, b, revision_id_list, revision):
4586
4643
 
4587
4644
 
4588
4645
class cmd_bind(Command):
4589
 
    """Convert the current branch into a checkout of the supplied branch.
 
4646
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
 
4647
    If no branch is supplied, rebind to the last bound location.
4590
4648
 
4591
4649
    Once converted into a checkout, commits must succeed on the master branch
4592
4650
    before they will be applied to the local branch.
4598
4656
 
4599
4657
    _see_also = ['checkouts', 'unbind']
4600
4658
    takes_args = ['location?']
4601
 
    takes_options = []
 
4659
    takes_options = ['directory']
4602
4660
 
4603
 
    def run(self, location=None):
4604
 
        b, relpath = Branch.open_containing(u'.')
 
4661
    def run(self, location=None, directory=u'.'):
 
4662
        b, relpath = Branch.open_containing(directory)
4605
4663
        if location is None:
4606
4664
            try:
4607
4665
                location = b.get_old_bound_location()
4626
4684
 
4627
4685
 
4628
4686
class cmd_unbind(Command):
4629
 
    """Convert the current checkout into a regular branch.
 
4687
    __doc__ = """Convert the current checkout into a regular branch.
4630
4688
 
4631
4689
    After unbinding, the local branch is considered independent and subsequent
4632
4690
    commits will be local only.
4634
4692
 
4635
4693
    _see_also = ['checkouts', 'bind']
4636
4694
    takes_args = []
4637
 
    takes_options = []
 
4695
    takes_options = ['directory']
4638
4696
 
4639
 
    def run(self):
4640
 
        b, relpath = Branch.open_containing(u'.')
 
4697
    def run(self, directory=u'.'):
 
4698
        b, relpath = Branch.open_containing(directory)
4641
4699
        if not b.unbind():
4642
4700
            raise errors.BzrCommandError('Local branch is not bound')
4643
4701
 
4644
4702
 
4645
4703
class cmd_uncommit(Command):
4646
 
    """Remove the last committed revision.
 
4704
    __doc__ = """Remove the last committed revision.
4647
4705
 
4648
4706
    --verbose will print out what is being removed.
4649
4707
    --dry-run will go through all the motions, but not actually
4689
4747
            b = control.open_branch()
4690
4748
 
4691
4749
        if tree is not None:
4692
 
            tree.lock_write()
4693
 
            self.add_cleanup(tree.unlock)
 
4750
            self.add_cleanup(tree.lock_write().unlock)
4694
4751
        else:
4695
 
            b.lock_write()
4696
 
            self.add_cleanup(b.unlock)
 
4752
            self.add_cleanup(b.lock_write().unlock)
4697
4753
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4698
4754
 
4699
4755
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4717
4773
                rev_id = b.get_rev_id(revno)
4718
4774
 
4719
4775
        if rev_id is None or _mod_revision.is_null(rev_id):
4720
 
            ui.ui_factory.note('No revisions to uncommit.')
 
4776
            self.outf.write('No revisions to uncommit.\n')
4721
4777
            return 1
4722
4778
 
4723
 
        log_collector = ui.ui_factory.make_output_stream()
4724
4779
        lf = log_formatter('short',
4725
 
                           to_file=log_collector,
 
4780
                           to_file=self.outf,
4726
4781
                           show_timezone='original')
4727
4782
 
4728
4783
        show_log(b,
4733
4788
                 end_revision=last_revno)
4734
4789
 
4735
4790
        if dry_run:
4736
 
            ui.ui_factory.note('Dry-run, pretending to remove the above revisions.')
 
4791
            self.outf.write('Dry-run, pretending to remove'
 
4792
                            ' the above revisions.\n')
4737
4793
        else:
4738
 
            ui.ui_factory.note('The above revision(s) will be removed.')
 
4794
            self.outf.write('The above revision(s) will be removed.\n')
4739
4795
 
4740
4796
        if not force:
4741
 
            if not ui.ui_factory.get_boolean('Are you sure [y/N]? '):
4742
 
                ui.ui_factory.note('Canceled')
 
4797
            if not ui.ui_factory.get_boolean('Are you sure'):
 
4798
                self.outf.write('Canceled')
4743
4799
                return 0
4744
4800
 
4745
4801
        mutter('Uncommitting from {%s} to {%s}',
4746
4802
               last_rev_id, rev_id)
4747
4803
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4748
4804
                 revno=revno, local=local)
4749
 
        ui.ui_factory.note('You can restore the old tip by running:\n'
4750
 
             '  bzr pull . -r revid:%s' % last_rev_id)
 
4805
        self.outf.write('You can restore the old tip by running:\n'
 
4806
             '  bzr pull . -r revid:%s\n' % last_rev_id)
4751
4807
 
4752
4808
 
4753
4809
class cmd_break_lock(Command):
4754
 
    """Break a dead lock on a repository, branch or working directory.
 
4810
    __doc__ = """Break a dead lock on a repository, branch or working directory.
4755
4811
 
4756
4812
    CAUTION: Locks should only be broken when you are sure that the process
4757
4813
    holding the lock has been stopped.
4776
4832
 
4777
4833
 
4778
4834
class cmd_wait_until_signalled(Command):
4779
 
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4835
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4780
4836
 
4781
4837
    This just prints a line to signal when it is ready, then blocks on stdin.
4782
4838
    """
4790
4846
 
4791
4847
 
4792
4848
class cmd_serve(Command):
4793
 
    """Run the bzr server."""
 
4849
    __doc__ = """Run the bzr server."""
4794
4850
 
4795
4851
    aliases = ['server']
4796
4852
 
4807
4863
                    'result in a dynamically allocated port.  The default port '
4808
4864
                    'depends on the protocol.',
4809
4865
               type=str),
4810
 
        Option('directory',
4811
 
               help='Serve contents of this directory.',
4812
 
               type=unicode),
 
4866
        custom_help('directory',
 
4867
               help='Serve contents of this directory.'),
4813
4868
        Option('allow-writes',
4814
4869
               help='By default the server is a readonly server.  Supplying '
4815
4870
                    '--allow-writes enables write access to the contents of '
4842
4897
 
4843
4898
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
4844
4899
            protocol=None):
4845
 
        from bzrlib.transport import get_transport, transport_server_registry
 
4900
        from bzrlib import transport
4846
4901
        if directory is None:
4847
4902
            directory = os.getcwd()
4848
4903
        if protocol is None:
4849
 
            protocol = transport_server_registry.get()
 
4904
            protocol = transport.transport_server_registry.get()
4850
4905
        host, port = self.get_host_and_port(port)
4851
4906
        url = urlutils.local_path_to_url(directory)
4852
4907
        if not allow_writes:
4853
4908
            url = 'readonly+' + url
4854
 
        transport = get_transport(url)
4855
 
        protocol(transport, host, port, inet)
 
4909
        t = transport.get_transport(url)
 
4910
        protocol(t, host, port, inet)
4856
4911
 
4857
4912
 
4858
4913
class cmd_join(Command):
4859
 
    """Combine a tree into its containing tree.
 
4914
    __doc__ = """Combine a tree into its containing tree.
4860
4915
 
4861
4916
    This command requires the target tree to be in a rich-root format.
4862
4917
 
4902
4957
 
4903
4958
 
4904
4959
class cmd_split(Command):
4905
 
    """Split a subdirectory of a tree into a separate tree.
 
4960
    __doc__ = """Split a subdirectory of a tree into a separate tree.
4906
4961
 
4907
4962
    This command will produce a target tree in a format that supports
4908
4963
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
4928
4983
 
4929
4984
 
4930
4985
class cmd_merge_directive(Command):
4931
 
    """Generate a merge directive for auto-merge tools.
 
4986
    __doc__ = """Generate a merge directive for auto-merge tools.
4932
4987
 
4933
4988
    A directive requests a merge to be performed, and also provides all the
4934
4989
    information necessary to do so.  This means it must either include a
4951
5006
    _see_also = ['send']
4952
5007
 
4953
5008
    takes_options = [
 
5009
        'directory',
4954
5010
        RegistryOption.from_kwargs('patch-type',
4955
5011
            'The type of patch to include in the directive.',
4956
5012
            title='Patch type',
4969
5025
    encoding_type = 'exact'
4970
5026
 
4971
5027
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4972
 
            sign=False, revision=None, mail_to=None, message=None):
 
5028
            sign=False, revision=None, mail_to=None, message=None,
 
5029
            directory=u'.'):
4973
5030
        from bzrlib.revision import ensure_null, NULL_REVISION
4974
5031
        include_patch, include_bundle = {
4975
5032
            'plain': (False, False),
4976
5033
            'diff': (True, False),
4977
5034
            'bundle': (True, True),
4978
5035
            }[patch_type]
4979
 
        branch = Branch.open('.')
 
5036
        branch = Branch.open(directory)
4980
5037
        stored_submit_branch = branch.get_submit_branch()
4981
5038
        if submit_branch is None:
4982
5039
            submit_branch = stored_submit_branch
5027
5084
 
5028
5085
 
5029
5086
class cmd_send(Command):
5030
 
    """Mail or create a merge-directive for submitting changes.
 
5087
    __doc__ = """Mail or create a merge-directive for submitting changes.
5031
5088
 
5032
5089
    A merge directive provides many things needed for requesting merges:
5033
5090
 
5067
5124
    given, in which case it is sent to a file.
5068
5125
 
5069
5126
    Mail is sent using your preferred mail program.  This should be transparent
5070
 
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
5127
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
5071
5128
    If the preferred client can't be found (or used), your editor will be used.
5072
5129
 
5073
5130
    To use a specific mail program, set the mail_client configuration option.
5115
5172
               short_name='f',
5116
5173
               type=unicode),
5117
5174
        Option('output', short_name='o',
5118
 
               help='Write merge directive to this file; '
 
5175
               help='Write merge directive to this file or directory; '
5119
5176
                    'use - for stdout.',
5120
5177
               type=unicode),
5121
5178
        Option('strict',
5144
5201
 
5145
5202
 
5146
5203
class cmd_bundle_revisions(cmd_send):
5147
 
    """Create a merge-directive for submitting changes.
 
5204
    __doc__ = """Create a merge-directive for submitting changes.
5148
5205
 
5149
5206
    A merge directive provides many things needed for requesting merges:
5150
5207
 
5217
5274
 
5218
5275
 
5219
5276
class cmd_tag(Command):
5220
 
    """Create, remove or modify a tag naming a revision.
 
5277
    __doc__ = """Create, remove or modify a tag naming a revision.
5221
5278
 
5222
5279
    Tags give human-meaningful names to revisions.  Commands that take a -r
5223
5280
    (--revision) option can be given -rtag:X, where X is any previously
5231
5288
 
5232
5289
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
5233
5290
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
 
5291
 
 
5292
    If no tag name is specified it will be determined through the 
 
5293
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
 
5294
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
 
5295
    details.
5234
5296
    """
5235
5297
 
5236
5298
    _see_also = ['commit', 'tags']
5237
 
    takes_args = ['tag_name']
 
5299
    takes_args = ['tag_name?']
5238
5300
    takes_options = [
5239
5301
        Option('delete',
5240
5302
            help='Delete this tag rather than placing it.',
5241
5303
            ),
5242
 
        Option('directory',
5243
 
            help='Branch in which to place the tag.',
5244
 
            short_name='d',
5245
 
            type=unicode,
5246
 
            ),
 
5304
        custom_help('directory',
 
5305
            help='Branch in which to place the tag.'),
5247
5306
        Option('force',
5248
5307
            help='Replace existing tags.',
5249
5308
            ),
5250
5309
        'revision',
5251
5310
        ]
5252
5311
 
5253
 
    def run(self, tag_name,
 
5312
    def run(self, tag_name=None,
5254
5313
            delete=None,
5255
5314
            directory='.',
5256
5315
            force=None,
5257
5316
            revision=None,
5258
5317
            ):
5259
5318
        branch, relpath = Branch.open_containing(directory)
5260
 
        branch.lock_write()
5261
 
        self.add_cleanup(branch.unlock)
 
5319
        self.add_cleanup(branch.lock_write().unlock)
5262
5320
        if delete:
 
5321
            if tag_name is None:
 
5322
                raise errors.BzrCommandError("No tag specified to delete.")
5263
5323
            branch.tags.delete_tag(tag_name)
5264
5324
            self.outf.write('Deleted tag %s.\n' % tag_name)
5265
5325
        else:
5271
5331
                revision_id = revision[0].as_revision_id(branch)
5272
5332
            else:
5273
5333
                revision_id = branch.last_revision()
 
5334
            if tag_name is None:
 
5335
                tag_name = branch.automatic_tag_name(revision_id)
 
5336
                if tag_name is None:
 
5337
                    raise errors.BzrCommandError(
 
5338
                        "Please specify a tag name.")
5274
5339
            if (not force) and branch.tags.has_tag(tag_name):
5275
5340
                raise errors.TagAlreadyExists(tag_name)
5276
5341
            branch.tags.set_tag(tag_name, revision_id)
5278
5343
 
5279
5344
 
5280
5345
class cmd_tags(Command):
5281
 
    """List tags.
 
5346
    __doc__ = """List tags.
5282
5347
 
5283
5348
    This command shows a table of tag names and the revisions they reference.
5284
5349
    """
5285
5350
 
5286
5351
    _see_also = ['tag']
5287
5352
    takes_options = [
5288
 
        Option('directory',
5289
 
            help='Branch whose tags should be displayed.',
5290
 
            short_name='d',
5291
 
            type=unicode,
5292
 
            ),
 
5353
        custom_help('directory',
 
5354
            help='Branch whose tags should be displayed.'),
5293
5355
        RegistryOption.from_kwargs('sort',
5294
5356
            'Sort tags by different criteria.', title='Sorting',
5295
5357
            alpha='Sort tags lexicographically (default).',
5312
5374
        if not tags:
5313
5375
            return
5314
5376
 
5315
 
        branch.lock_read()
5316
 
        self.add_cleanup(branch.unlock)
 
5377
        self.add_cleanup(branch.lock_read().unlock)
5317
5378
        if revision:
5318
5379
            graph = branch.repository.get_graph()
5319
5380
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
5352
5413
 
5353
5414
 
5354
5415
class cmd_reconfigure(Command):
5355
 
    """Reconfigure the type of a bzr directory.
 
5416
    __doc__ = """Reconfigure the type of a bzr directory.
5356
5417
 
5357
5418
    A target configuration must be specified.
5358
5419
 
5443
5504
 
5444
5505
 
5445
5506
class cmd_switch(Command):
5446
 
    """Set the branch of a checkout and update.
 
5507
    __doc__ = """Set the branch of a checkout and update.
5447
5508
 
5448
5509
    For lightweight checkouts, this changes the branch being referenced.
5449
5510
    For heavyweight checkouts, this checks that there are no local commits
5466
5527
    """
5467
5528
 
5468
5529
    takes_args = ['to_location?']
5469
 
    takes_options = [Option('force',
 
5530
    takes_options = ['directory',
 
5531
                     Option('force',
5470
5532
                        help='Switch even if local commits will be lost.'),
5471
5533
                     'revision',
5472
5534
                     Option('create-branch', short_name='b',
5475
5537
                    ]
5476
5538
 
5477
5539
    def run(self, to_location=None, force=False, create_branch=False,
5478
 
            revision=None):
 
5540
            revision=None, directory=u'.'):
5479
5541
        from bzrlib import switch
5480
 
        tree_location = '.'
 
5542
        tree_location = directory
5481
5543
        revision = _get_one_revision('switch', revision)
5482
5544
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5483
5545
        if to_location is None:
5484
5546
            if revision is None:
5485
5547
                raise errors.BzrCommandError('You must supply either a'
5486
5548
                                             ' revision or a location')
5487
 
            to_location = '.'
 
5549
            to_location = tree_location
5488
5550
        try:
5489
5551
            branch = control_dir.open_branch()
5490
5552
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5539
5601
 
5540
5602
 
5541
5603
class cmd_view(Command):
5542
 
    """Manage filtered views.
 
5604
    __doc__ = """Manage filtered views.
5543
5605
 
5544
5606
    Views provide a mask over the tree so that users can focus on
5545
5607
    a subset of a tree when doing their work. After creating a view,
5625
5687
            name=None,
5626
5688
            switch=None,
5627
5689
            ):
5628
 
        tree, file_list = tree_files(file_list, apply_view=False)
 
5690
        tree, file_list = WorkingTree.open_containing_paths(file_list,
 
5691
            apply_view=False)
5629
5692
        current_view, view_dict = tree.views.get_view_info()
5630
5693
        if name is None:
5631
5694
            name = current_view
5693
5756
 
5694
5757
 
5695
5758
class cmd_hooks(Command):
5696
 
    """Show hooks."""
 
5759
    __doc__ = """Show hooks."""
5697
5760
 
5698
5761
    hidden = True
5699
5762
 
5712
5775
                    self.outf.write("    <no hooks installed>\n")
5713
5776
 
5714
5777
 
 
5778
class cmd_remove_branch(Command):
 
5779
    __doc__ = """Remove a branch.
 
5780
 
 
5781
    This will remove the branch from the specified location but 
 
5782
    will keep any working tree or repository in place.
 
5783
 
 
5784
    :Examples:
 
5785
 
 
5786
      Remove the branch at repo/trunk::
 
5787
 
 
5788
        bzr remove-branch repo/trunk
 
5789
 
 
5790
    """
 
5791
 
 
5792
    takes_args = ["location?"]
 
5793
 
 
5794
    aliases = ["rmbranch"]
 
5795
 
 
5796
    def run(self, location=None):
 
5797
        if location is None:
 
5798
            location = "."
 
5799
        branch = Branch.open_containing(location)[0]
 
5800
        branch.bzrdir.destroy_branch()
 
5801
        
 
5802
 
5715
5803
class cmd_shelve(Command):
5716
 
    """Temporarily set aside some changes from the current tree.
 
5804
    __doc__ = """Temporarily set aside some changes from the current tree.
5717
5805
 
5718
5806
    Shelve allows you to temporarily put changes you've made "on the shelf",
5719
5807
    ie. out of the way, until a later time when you can bring them back from
5740
5828
    takes_args = ['file*']
5741
5829
 
5742
5830
    takes_options = [
 
5831
        'directory',
5743
5832
        'revision',
5744
5833
        Option('all', help='Shelve all changes.'),
5745
5834
        'message',
5754
5843
    _see_also = ['unshelve']
5755
5844
 
5756
5845
    def run(self, revision=None, all=False, file_list=None, message=None,
5757
 
            writer=None, list=False, destroy=False):
 
5846
            writer=None, list=False, destroy=False, directory=u'.'):
5758
5847
        if list:
5759
5848
            return self.run_for_list()
5760
5849
        from bzrlib.shelf_ui import Shelver
5762
5851
            writer = bzrlib.option.diff_writer_registry.get()
5763
5852
        try:
5764
5853
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5765
 
                file_list, message, destroy=destroy)
 
5854
                file_list, message, destroy=destroy, directory=directory)
5766
5855
            try:
5767
5856
                shelver.run()
5768
5857
            finally:
5772
5861
 
5773
5862
    def run_for_list(self):
5774
5863
        tree = WorkingTree.open_containing('.')[0]
5775
 
        tree.lock_read()
5776
 
        self.add_cleanup(tree.unlock)
 
5864
        self.add_cleanup(tree.lock_read().unlock)
5777
5865
        manager = tree.get_shelf_manager()
5778
5866
        shelves = manager.active_shelves()
5779
5867
        if len(shelves) == 0:
5788
5876
 
5789
5877
 
5790
5878
class cmd_unshelve(Command):
5791
 
    """Restore shelved changes.
 
5879
    __doc__ = """Restore shelved changes.
5792
5880
 
5793
5881
    By default, the most recently shelved changes are restored. However if you
5794
5882
    specify a shelf by id those changes will be restored instead.  This works
5797
5885
 
5798
5886
    takes_args = ['shelf_id?']
5799
5887
    takes_options = [
 
5888
        'directory',
5800
5889
        RegistryOption.from_kwargs(
5801
5890
            'action', help="The action to perform.",
5802
5891
            enum_switch=False, value_switches=True,
5810
5899
    ]
5811
5900
    _see_also = ['shelve']
5812
5901
 
5813
 
    def run(self, shelf_id=None, action='apply'):
 
5902
    def run(self, shelf_id=None, action='apply', directory=u'.'):
5814
5903
        from bzrlib.shelf_ui import Unshelver
5815
 
        unshelver = Unshelver.from_args(shelf_id, action)
 
5904
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5816
5905
        try:
5817
5906
            unshelver.run()
5818
5907
        finally:
5820
5909
 
5821
5910
 
5822
5911
class cmd_clean_tree(Command):
5823
 
    """Remove unwanted files from working tree.
 
5912
    __doc__ = """Remove unwanted files from working tree.
5824
5913
 
5825
5914
    By default, only unknown files, not ignored files, are deleted.  Versioned
5826
5915
    files are never deleted.
5834
5923
 
5835
5924
    To check what clean-tree will do, use --dry-run.
5836
5925
    """
5837
 
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5926
    takes_options = ['directory',
 
5927
                     Option('ignored', help='Delete all ignored files.'),
5838
5928
                     Option('detritus', help='Delete conflict files, merge'
5839
5929
                            ' backups, and failed selftest dirs.'),
5840
5930
                     Option('unknown',
5843
5933
                            ' deleting them.'),
5844
5934
                     Option('force', help='Do not prompt before deleting.')]
5845
5935
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5846
 
            force=False):
 
5936
            force=False, directory=u'.'):
5847
5937
        from bzrlib.clean_tree import clean_tree
5848
5938
        if not (unknown or ignored or detritus):
5849
5939
            unknown = True
5850
5940
        if dry_run:
5851
5941
            force = True
5852
 
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
5853
 
                   dry_run=dry_run, no_prompt=force)
 
5942
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
5943
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
5854
5944
 
5855
5945
 
5856
5946
class cmd_reference(Command):
5857
 
    """list, view and set branch locations for nested trees.
 
5947
    __doc__ = """list, view and set branch locations for nested trees.
5858
5948
 
5859
5949
    If no arguments are provided, lists the branch locations for nested trees.
5860
5950
    If one argument is provided, display the branch location for that tree.
5900
5990
            self.outf.write('%s %s\n' % (path, location))
5901
5991
 
5902
5992
 
5903
 
# these get imported and then picked up by the scan for cmd_*
5904
 
# TODO: Some more consistent way to split command definitions across files;
5905
 
# we do need to load at least some information about them to know of
5906
 
# aliases.  ideally we would avoid loading the implementation until the
5907
 
# details were needed.
5908
 
from bzrlib.cmd_version_info import cmd_version_info
5909
 
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
5910
 
from bzrlib.bundle.commands import (
5911
 
    cmd_bundle_info,
5912
 
    )
5913
 
from bzrlib.foreign import cmd_dpush
5914
 
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
5993
def _register_lazy_builtins():
 
5994
    # register lazy builtins from other modules; called at startup and should
 
5995
    # be only called once.
 
5996
    for (name, aliases, module_name) in [
 
5997
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
 
5998
        ('cmd_dpush', [], 'bzrlib.foreign'),
 
5999
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
 
6000
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
 
6001
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
 
6002
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
 
6003
        ]:
 
6004
        builtin_command_registry.register_lazy(name, aliases, module_name)