~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-07-29 10:44:42 UTC
  • mfrom: (5361.1.1 2.3-lp-home)
  • Revision ID: pqm@pqm.ubuntu.com-20100729104442-5g1m4pumcss037ic
(spiv) Expand lp:~/ to lp:~username/ if a user has already logged in. (John
 A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
18
18
 
19
19
import os
20
20
 
21
 
import bzrlib.bzrdir
22
 
 
23
21
from bzrlib.lazy_import import lazy_import
24
22
lazy_import(globals(), """
 
23
import codecs
25
24
import cStringIO
26
25
import sys
27
26
import time
31
30
    bugtracker,
32
31
    bundle,
33
32
    btree_index,
34
 
    controldir,
 
33
    bzrdir,
35
34
    directory_service,
36
35
    delta,
37
 
    config as _mod_config,
 
36
    config,
38
37
    errors,
39
38
    globbing,
40
39
    hooks,
46
45
    rename_map,
47
46
    revision as _mod_revision,
48
47
    static_tuple,
 
48
    symbol_versioning,
49
49
    timestamp,
50
50
    transport,
51
51
    ui,
52
52
    urlutils,
53
53
    views,
54
 
    gpg,
55
54
    )
56
55
from bzrlib.branch import Branch
57
56
from bzrlib.conflicts import ConflictList
59
58
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
60
59
from bzrlib.smtp_connection import SMTPConnection
61
60
from bzrlib.workingtree import WorkingTree
62
 
from bzrlib.i18n import gettext, ngettext
63
61
""")
64
62
 
65
63
from bzrlib.commands import (
75
73
    _parse_revision_str,
76
74
    )
77
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
78
 
from bzrlib import (
79
 
    symbol_versioning,
80
 
    )
81
76
 
82
77
 
83
78
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
115
110
            if view_files:
116
111
                file_list = view_files
117
112
                view_str = views.view_display_str(view_files)
118
 
                note(gettext("Ignoring files outside view. View is %s") % view_str)
 
113
                note("Ignoring files outside view. View is %s" % view_str)
119
114
    return tree, file_list
120
115
 
121
116
 
123
118
    if revisions is None:
124
119
        return None
125
120
    if len(revisions) != 1:
126
 
        raise errors.BzrCommandError(gettext(
127
 
            'bzr %s --revision takes exactly one revision identifier') % (
 
121
        raise errors.BzrCommandError(
 
122
            'bzr %s --revision takes exactly one revision identifier' % (
128
123
                command_name,))
129
124
    return revisions[0]
130
125
 
199
194
    the --directory option is used to specify a different branch."""
200
195
    if directory is not None:
201
196
        return (None, Branch.open(directory), filename)
202
 
    return controldir.ControlDir.open_containing_tree_or_branch(filename)
 
197
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
203
198
 
204
199
 
205
200
# TODO: Make sure no commands unconditionally use the working directory as a
235
230
    unknown
236
231
        Not versioned and not matching an ignore pattern.
237
232
 
238
 
    Additionally for directories, symlinks and files with a changed
239
 
    executable bit, Bazaar indicates their type using a trailing
240
 
    character: '/', '@' or '*' respectively. These decorations can be
241
 
    disabled using the '--no-classify' option.
 
233
    Additionally for directories, symlinks and files with an executable
 
234
    bit, Bazaar indicates their type using a trailing character: '/', '@'
 
235
    or '*' respectively.
242
236
 
243
237
    To see ignored files use 'bzr ignored'.  For details on the
244
238
    changes to file texts, use 'bzr diff'.
257
251
    To skip the display of pending merge information altogether, use
258
252
    the no-pending option or specify a file/directory.
259
253
 
260
 
    To compare the working directory to a specific revision, pass a
261
 
    single revision to the revision argument.
262
 
 
263
 
    To see which files have changed in a specific revision, or between
264
 
    two revisions, pass a revision range to the revision argument.
265
 
    This will produce the same results as calling 'bzr diff --summarize'.
 
254
    If a revision argument is given, the status is calculated against
 
255
    that revision, or between two revisions if two are provided.
266
256
    """
267
257
 
268
258
    # TODO: --no-recurse, --recurse options
275
265
                            short_name='V'),
276
266
                     Option('no-pending', help='Don\'t show pending merges.',
277
267
                           ),
278
 
                     Option('no-classify',
279
 
                            help='Do not mark object type using indicator.',
280
 
                           ),
281
268
                     ]
282
269
    aliases = ['st', 'stat']
283
270
 
286
273
 
287
274
    @display_command
288
275
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
289
 
            versioned=False, no_pending=False, verbose=False,
290
 
            no_classify=False):
 
276
            versioned=False, no_pending=False, verbose=False):
291
277
        from bzrlib.status import show_tree_status
292
278
 
293
279
        if revision and len(revision) > 2:
294
 
            raise errors.BzrCommandError(gettext('bzr status --revision takes exactly'
295
 
                                         ' one or two revision specifiers'))
 
280
            raise errors.BzrCommandError('bzr status --revision takes exactly'
 
281
                                         ' one or two revision specifiers')
296
282
 
297
283
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
298
284
        # Avoid asking for specific files when that is not needed.
307
293
        show_tree_status(tree, show_ids=show_ids,
308
294
                         specific_files=relfile_list, revision=revision,
309
295
                         to_file=self.outf, short=short, versioned=versioned,
310
 
                         show_pending=(not no_pending), verbose=verbose,
311
 
                         classify=not no_classify)
 
296
                         show_pending=(not no_pending), verbose=verbose)
312
297
 
313
298
 
314
299
class cmd_cat_revision(Command):
335
320
    @display_command
336
321
    def run(self, revision_id=None, revision=None, directory=u'.'):
337
322
        if revision_id is not None and revision is not None:
338
 
            raise errors.BzrCommandError(gettext('You can only supply one of'
339
 
                                         ' revision_id or --revision'))
 
323
            raise errors.BzrCommandError('You can only supply one of'
 
324
                                         ' revision_id or --revision')
340
325
        if revision_id is None and revision is None:
341
 
            raise errors.BzrCommandError(gettext('You must supply either'
342
 
                                         ' --revision or a revision_id'))
343
 
 
344
 
        b = controldir.ControlDir.open_containing_tree_or_branch(directory)[1]
 
326
            raise errors.BzrCommandError('You must supply either'
 
327
                                         ' --revision or a revision_id')
 
328
        b = WorkingTree.open_containing(directory)[0].branch
345
329
 
346
330
        revisions = b.repository.revisions
347
331
        if revisions is None:
348
 
            raise errors.BzrCommandError(gettext('Repository %r does not support '
349
 
                'access to raw revision texts'))
 
332
            raise errors.BzrCommandError('Repository %r does not support '
 
333
                'access to raw revision texts')
350
334
 
351
335
        b.repository.lock_read()
352
336
        try:
356
340
                try:
357
341
                    self.print_revision(revisions, revision_id)
358
342
                except errors.NoSuchRevision:
359
 
                    msg = gettext("The repository {0} contains no revision {1}.").format(
 
343
                    msg = "The repository %s contains no revision %s." % (
360
344
                        b.repository.base, revision_id)
361
345
                    raise errors.BzrCommandError(msg)
362
346
            elif revision is not None:
363
347
                for rev in revision:
364
348
                    if rev is None:
365
349
                        raise errors.BzrCommandError(
366
 
                            gettext('You cannot specify a NULL revision.'))
 
350
                            'You cannot specify a NULL revision.')
367
351
                    rev_id = rev.as_revision_id(b)
368
352
                    self.print_revision(revisions, rev_id)
369
353
        finally:
425
409
                self.outf.write(page_bytes[:header_end])
426
410
                page_bytes = data
427
411
            self.outf.write('\nPage %d\n' % (page_idx,))
428
 
            if len(page_bytes) == 0:
429
 
                self.outf.write('(empty)\n');
430
 
            else:
431
 
                decomp_bytes = zlib.decompress(page_bytes)
432
 
                self.outf.write(decomp_bytes)
433
 
                self.outf.write('\n')
 
412
            decomp_bytes = zlib.decompress(page_bytes)
 
413
            self.outf.write(decomp_bytes)
 
414
            self.outf.write('\n')
434
415
 
435
416
    def _dump_entries(self, trans, basename):
436
417
        try:
475
456
            location_list=['.']
476
457
 
477
458
        for location in location_list:
478
 
            d = controldir.ControlDir.open(location)
479
 
 
 
459
            d = bzrdir.BzrDir.open(location)
 
460
            
480
461
            try:
481
462
                working = d.open_workingtree()
482
463
            except errors.NoWorkingTree:
483
 
                raise errors.BzrCommandError(gettext("No working tree to remove"))
 
464
                raise errors.BzrCommandError("No working tree to remove")
484
465
            except errors.NotLocalUrl:
485
 
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
486
 
                                             " of a remote path"))
 
466
                raise errors.BzrCommandError("You cannot remove the working tree"
 
467
                                             " of a remote path")
487
468
            if not force:
488
469
                if (working.has_changes()):
489
470
                    raise errors.UncommittedChanges(working)
491
472
                    raise errors.ShelvedChanges(working)
492
473
 
493
474
            if working.user_url != working.branch.user_url:
494
 
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
495
 
                                             " from a lightweight checkout"))
 
475
                raise errors.BzrCommandError("You cannot remove the working tree"
 
476
                                             " from a lightweight checkout")
496
477
 
497
478
            d.destroy_workingtree()
498
479
 
499
480
 
500
 
class cmd_repair_workingtree(Command):
501
 
    __doc__ = """Reset the working tree state file.
502
 
 
503
 
    This is not meant to be used normally, but more as a way to recover from
504
 
    filesystem corruption, etc. This rebuilds the working inventory back to a
505
 
    'known good' state. Any new modifications (adding a file, renaming, etc)
506
 
    will be lost, though modified files will still be detected as such.
507
 
 
508
 
    Most users will want something more like "bzr revert" or "bzr update"
509
 
    unless the state file has become corrupted.
510
 
 
511
 
    By default this attempts to recover the current state by looking at the
512
 
    headers of the state file. If the state file is too corrupted to even do
513
 
    that, you can supply --revision to force the state of the tree.
514
 
    """
515
 
 
516
 
    takes_options = ['revision', 'directory',
517
 
        Option('force',
518
 
               help='Reset the tree even if it doesn\'t appear to be'
519
 
                    ' corrupted.'),
520
 
    ]
521
 
    hidden = True
522
 
 
523
 
    def run(self, revision=None, directory='.', force=False):
524
 
        tree, _ = WorkingTree.open_containing(directory)
525
 
        self.add_cleanup(tree.lock_tree_write().unlock)
526
 
        if not force:
527
 
            try:
528
 
                tree.check_state()
529
 
            except errors.BzrError:
530
 
                pass # There seems to be a real error here, so we'll reset
531
 
            else:
532
 
                # Refuse
533
 
                raise errors.BzrCommandError(gettext(
534
 
                    'The tree does not appear to be corrupt. You probably'
535
 
                    ' want "bzr revert" instead. Use "--force" if you are'
536
 
                    ' sure you want to reset the working tree.'))
537
 
        if revision is None:
538
 
            revision_ids = None
539
 
        else:
540
 
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
541
 
        try:
542
 
            tree.reset_state(revision_ids)
543
 
        except errors.BzrError, e:
544
 
            if revision_ids is None:
545
 
                extra = (gettext(', the header appears corrupt, try passing -r -1'
546
 
                         ' to set the state to the last commit'))
547
 
            else:
548
 
                extra = ''
549
 
            raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
550
 
 
551
 
 
552
481
class cmd_revno(Command):
553
482
    __doc__ = """Show current revision number.
554
483
 
559
488
    takes_args = ['location?']
560
489
    takes_options = [
561
490
        Option('tree', help='Show revno of working tree'),
562
 
        'revision',
563
491
        ]
564
492
 
565
493
    @display_command
566
 
    def run(self, tree=False, location=u'.', revision=None):
567
 
        if revision is not None and tree:
568
 
            raise errors.BzrCommandError(gettext("--tree and --revision can "
569
 
                "not be used together"))
570
 
 
 
494
    def run(self, tree=False, location=u'.'):
571
495
        if tree:
572
496
            try:
573
497
                wt = WorkingTree.open_containing(location)[0]
574
498
                self.add_cleanup(wt.lock_read().unlock)
575
499
            except (errors.NoWorkingTree, errors.NotLocalUrl):
576
500
                raise errors.NoWorkingTree(location)
577
 
            b = wt.branch
578
501
            revid = wt.last_revision()
 
502
            try:
 
503
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
504
            except errors.NoSuchRevision:
 
505
                revno_t = ('???',)
 
506
            revno = ".".join(str(n) for n in revno_t)
579
507
        else:
580
508
            b = Branch.open_containing(location)[0]
581
509
            self.add_cleanup(b.lock_read().unlock)
582
 
            if revision:
583
 
                if len(revision) != 1:
584
 
                    raise errors.BzrCommandError(gettext(
585
 
                        "Tags can only be placed on a single revision, "
586
 
                        "not on a range"))
587
 
                revid = revision[0].as_revision_id(b)
588
 
            else:
589
 
                revid = b.last_revision()
590
 
        try:
591
 
            revno_t = b.revision_id_to_dotted_revno(revid)
592
 
        except errors.NoSuchRevision:
593
 
            revno_t = ('???',)
594
 
        revno = ".".join(str(n) for n in revno_t)
 
510
            revno = b.revno()
595
511
        self.cleanup_now()
596
 
        self.outf.write(revno + '\n')
 
512
        self.outf.write(str(revno) + '\n')
597
513
 
598
514
 
599
515
class cmd_revision_info(Command):
668
584
    are added.  This search proceeds recursively into versioned
669
585
    directories.  If no names are given '.' is assumed.
670
586
 
671
 
    A warning will be printed when nested trees are encountered,
672
 
    unless they are explicitly ignored.
673
 
 
674
587
    Therefore simply saying 'bzr add' will version all files that
675
588
    are currently unknown.
676
589
 
692
605
    
693
606
    Any files matching patterns in the ignore list will not be added
694
607
    unless they are explicitly mentioned.
695
 
    
696
 
    In recursive mode, files larger than the configuration option 
697
 
    add.maximum_file_size will be skipped. Named items are never skipped due
698
 
    to file size.
699
608
    """
700
609
    takes_args = ['file*']
701
610
    takes_options = [
728
637
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
729
638
                          to_file=self.outf, should_print=(not is_quiet()))
730
639
        else:
731
 
            action = bzrlib.add.AddWithSkipLargeAction(to_file=self.outf,
 
640
            action = bzrlib.add.AddAction(to_file=self.outf,
732
641
                should_print=(not is_quiet()))
733
642
 
734
643
        if base_tree:
741
650
            if verbose:
742
651
                for glob in sorted(ignored.keys()):
743
652
                    for path in ignored[glob]:
744
 
                        self.outf.write(
745
 
                         gettext("ignored {0} matching \"{1}\"\n").format(
746
 
                         path, glob))
 
653
                        self.outf.write("ignored %s matching \"%s\"\n"
 
654
                                        % (path, glob))
747
655
 
748
656
 
749
657
class cmd_mkdir(Command):
763
671
            if id != None:
764
672
                os.mkdir(d)
765
673
                wt.add([dd])
766
 
                if not is_quiet():
767
 
                    self.outf.write(gettext('added %s\n') % d)
 
674
                self.outf.write('added %s\n' % d)
768
675
            else:
769
676
                raise errors.NotVersionedError(path=base)
770
677
 
808
715
    @display_command
809
716
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
810
717
        if kind and kind not in ['file', 'directory', 'symlink']:
811
 
            raise errors.BzrCommandError(gettext('invalid kind %r specified') % (kind,))
 
718
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
812
719
 
813
720
        revision = _get_one_revision('inventory', revision)
814
721
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
827
734
                                      require_versioned=True)
828
735
            # find_ids_across_trees may include some paths that don't
829
736
            # exist in 'tree'.
830
 
            entries = sorted(
831
 
                (tree.id2path(file_id), tree.inventory[file_id])
832
 
                for file_id in file_ids if tree.has_id(file_id))
 
737
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
738
                             for file_id in file_ids if file_id in tree)
833
739
        else:
834
740
            entries = tree.inventory.entries()
835
741
 
878
784
        if auto:
879
785
            return self.run_auto(names_list, after, dry_run)
880
786
        elif dry_run:
881
 
            raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
 
787
            raise errors.BzrCommandError('--dry-run requires --auto.')
882
788
        if names_list is None:
883
789
            names_list = []
884
790
        if len(names_list) < 2:
885
 
            raise errors.BzrCommandError(gettext("missing file argument"))
 
791
            raise errors.BzrCommandError("missing file argument")
886
792
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
887
793
        self.add_cleanup(tree.lock_tree_write().unlock)
888
794
        self._run(tree, names_list, rel_names, after)
889
795
 
890
796
    def run_auto(self, names_list, after, dry_run):
891
797
        if names_list is not None and len(names_list) > 1:
892
 
            raise errors.BzrCommandError(gettext('Only one path may be specified to'
893
 
                                         ' --auto.'))
 
798
            raise errors.BzrCommandError('Only one path may be specified to'
 
799
                                         ' --auto.')
894
800
        if after:
895
 
            raise errors.BzrCommandError(gettext('--after cannot be specified with'
896
 
                                         ' --auto.'))
 
801
            raise errors.BzrCommandError('--after cannot be specified with'
 
802
                                         ' --auto.')
897
803
        work_tree, file_list = WorkingTree.open_containing_paths(
898
804
            names_list, default_directory='.')
899
805
        self.add_cleanup(work_tree.lock_tree_write().unlock)
929
835
                    self.outf.write("%s => %s\n" % (src, dest))
930
836
        else:
931
837
            if len(names_list) != 2:
932
 
                raise errors.BzrCommandError(gettext('to mv multiple files the'
 
838
                raise errors.BzrCommandError('to mv multiple files the'
933
839
                                             ' destination must be a versioned'
934
 
                                             ' directory'))
 
840
                                             ' directory')
935
841
 
936
842
            # for cicp file-systems: the src references an existing inventory
937
843
            # item:
996
902
    match the remote one, use pull --overwrite. This will work even if the two
997
903
    branches have diverged.
998
904
 
999
 
    If there is no default location set, the first pull will set it (use
1000
 
    --no-remember to avoid setting it). After that, you can omit the
1001
 
    location to use the default.  To change the default, use --remember. The
1002
 
    value will only be saved if the remote location can be accessed.
1003
 
 
1004
 
    The --verbose option will display the revisions pulled using the log_format
1005
 
    configuration option. You can use a different format by overriding it with
1006
 
    -Olog_format=<other_format>.
 
905
    If there is no default location set, the first pull will set it.  After
 
906
    that, you can omit the location to use the default.  To change the
 
907
    default, use --remember. The value will only be saved if the remote
 
908
    location can be accessed.
1007
909
 
1008
910
    Note: The location can be specified either in the form of a branch,
1009
911
    or in the form of a path to a file containing a merge directive generated
1022
924
                 "branch.  Local pulls are not applied to "
1023
925
                 "the master branch."
1024
926
            ),
1025
 
        Option('show-base',
1026
 
            help="Show base revision text in conflicts.")
1027
927
        ]
1028
928
    takes_args = ['location?']
1029
929
    encoding_type = 'replace'
1030
930
 
1031
 
    def run(self, location=None, remember=None, overwrite=False,
 
931
    def run(self, location=None, remember=False, overwrite=False,
1032
932
            revision=None, verbose=False,
1033
 
            directory=None, local=False,
1034
 
            show_base=False):
 
933
            directory=None, local=False):
1035
934
        # FIXME: too much stuff is in the command class
1036
935
        revision_id = None
1037
936
        mergeable = None
1046
945
            branch_to = Branch.open_containing(directory)[0]
1047
946
            self.add_cleanup(branch_to.lock_write().unlock)
1048
947
 
1049
 
        if tree_to is None and show_base:
1050
 
            raise errors.BzrCommandError(gettext("Need working tree for --show-base."))
1051
 
 
1052
948
        if local and not branch_to.get_bound_location():
1053
949
            raise errors.LocalRequiresBoundBranch()
1054
950
 
1063
959
        stored_loc = branch_to.get_parent()
1064
960
        if location is None:
1065
961
            if stored_loc is None:
1066
 
                raise errors.BzrCommandError(gettext("No pull location known or"
1067
 
                                             " specified."))
 
962
                raise errors.BzrCommandError("No pull location known or"
 
963
                                             " specified.")
1068
964
            else:
1069
965
                display_url = urlutils.unescape_for_display(stored_loc,
1070
966
                        self.outf.encoding)
1071
967
                if not is_quiet():
1072
 
                    self.outf.write(gettext("Using saved parent location: %s\n") % display_url)
 
968
                    self.outf.write("Using saved parent location: %s\n" % display_url)
1073
969
                location = stored_loc
1074
970
 
1075
971
        revision = _get_one_revision('pull', revision)
1076
972
        if mergeable is not None:
1077
973
            if revision is not None:
1078
 
                raise errors.BzrCommandError(gettext(
1079
 
                    'Cannot use -r with merge directives or bundles'))
 
974
                raise errors.BzrCommandError(
 
975
                    'Cannot use -r with merge directives or bundles')
1080
976
            mergeable.install_revisions(branch_to.repository)
1081
977
            base_revision_id, revision_id, verified = \
1082
978
                mergeable.get_merge_request(branch_to.repository)
1085
981
            branch_from = Branch.open(location,
1086
982
                possible_transports=possible_transports)
1087
983
            self.add_cleanup(branch_from.lock_read().unlock)
1088
 
            # Remembers if asked explicitly or no previous location is set
1089
 
            if (remember
1090
 
                or (remember is None and branch_to.get_parent() is None)):
 
984
 
 
985
            if branch_to.get_parent() is None or remember:
1091
986
                branch_to.set_parent(branch_from.base)
1092
987
 
1093
988
        if revision is not None:
1100
995
                view_info=view_info)
1101
996
            result = tree_to.pull(
1102
997
                branch_from, overwrite, revision_id, change_reporter,
1103
 
                local=local, show_base=show_base)
 
998
                possible_transports=possible_transports, local=local)
1104
999
        else:
1105
1000
            result = branch_to.pull(
1106
1001
                branch_from, overwrite, revision_id, local=local)
1110
1005
            log.show_branch_change(
1111
1006
                branch_to, self.outf, result.old_revno,
1112
1007
                result.old_revid)
1113
 
        if getattr(result, 'tag_conflicts', None):
1114
 
            return 1
1115
 
        else:
1116
 
            return 0
1117
1008
 
1118
1009
 
1119
1010
class cmd_push(Command):
1136
1027
    do a merge (see bzr help merge) from the other branch, and commit that.
1137
1028
    After that you will be able to do a push without '--overwrite'.
1138
1029
 
1139
 
    If there is no default push location set, the first push will set it (use
1140
 
    --no-remember to avoid setting it).  After that, you can omit the
1141
 
    location to use the default.  To change the default, use --remember. The
1142
 
    value will only be saved if the remote location can be accessed.
1143
 
 
1144
 
    The --verbose option will display the revisions pushed using the log_format
1145
 
    configuration option. You can use a different format by overriding it with
1146
 
    -Olog_format=<other_format>.
 
1030
    If there is no default push location set, the first push will set it.
 
1031
    After that, you can omit the location to use the default.  To change the
 
1032
    default, use --remember. The value will only be saved if the remote
 
1033
    location can be accessed.
1147
1034
    """
1148
1035
 
1149
1036
    _see_also = ['pull', 'update', 'working-trees']
1170
1057
        Option('strict',
1171
1058
               help='Refuse to push if there are uncommitted changes in'
1172
1059
               ' the working tree, --no-strict disables the check.'),
1173
 
        Option('no-tree',
1174
 
               help="Don't populate the working tree, even for protocols"
1175
 
               " that support it."),
1176
1060
        ]
1177
1061
    takes_args = ['location?']
1178
1062
    encoding_type = 'replace'
1179
1063
 
1180
 
    def run(self, location=None, remember=None, overwrite=False,
 
1064
    def run(self, location=None, remember=False, overwrite=False,
1181
1065
        create_prefix=False, verbose=False, revision=None,
1182
1066
        use_existing_dir=False, directory=None, stacked_on=None,
1183
 
        stacked=False, strict=None, no_tree=False):
 
1067
        stacked=False, strict=None):
1184
1068
        from bzrlib.push import _show_push_branch
1185
1069
 
1186
1070
        if directory is None:
1187
1071
            directory = '.'
1188
1072
        # Get the source branch
1189
1073
        (tree, br_from,
1190
 
         _unused) = controldir.ControlDir.open_containing_tree_or_branch(directory)
 
1074
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1191
1075
        # Get the tip's revision_id
1192
1076
        revision = _get_one_revision('push', revision)
1193
1077
        if revision is not None:
1214
1098
                    # error by the feedback given to them. RBC 20080227.
1215
1099
                    stacked_on = parent_url
1216
1100
            if not stacked_on:
1217
 
                raise errors.BzrCommandError(gettext(
1218
 
                    "Could not determine branch to refer to."))
 
1101
                raise errors.BzrCommandError(
 
1102
                    "Could not determine branch to refer to.")
1219
1103
 
1220
1104
        # Get the destination location
1221
1105
        if location is None:
1222
1106
            stored_loc = br_from.get_push_location()
1223
1107
            if stored_loc is None:
1224
 
                raise errors.BzrCommandError(gettext(
1225
 
                    "No push location known or specified."))
 
1108
                raise errors.BzrCommandError(
 
1109
                    "No push location known or specified.")
1226
1110
            else:
1227
1111
                display_url = urlutils.unescape_for_display(stored_loc,
1228
1112
                        self.outf.encoding)
1229
 
                note(gettext("Using saved push location: %s") % display_url)
 
1113
                self.outf.write("Using saved push location: %s\n" % display_url)
1230
1114
                location = stored_loc
1231
1115
 
1232
1116
        _show_push_branch(br_from, revision_id, location, self.outf,
1233
1117
            verbose=verbose, overwrite=overwrite, remember=remember,
1234
1118
            stacked_on=stacked_on, create_prefix=create_prefix,
1235
 
            use_existing_dir=use_existing_dir, no_tree=no_tree)
 
1119
            use_existing_dir=use_existing_dir)
1236
1120
 
1237
1121
 
1238
1122
class cmd_branch(Command):
1247
1131
 
1248
1132
    To retrieve the branch as of a particular revision, supply the --revision
1249
1133
    parameter, as in "branch foo/bar -r 5".
1250
 
 
1251
 
    The synonyms 'clone' and 'get' for this command are deprecated.
1252
1134
    """
1253
1135
 
1254
1136
    _see_also = ['checkout']
1284
1166
            files_from=None):
1285
1167
        from bzrlib import switch as _mod_switch
1286
1168
        from bzrlib.tag import _merge_tags_if_possible
1287
 
        if self.invoked_as in ['get', 'clone']:
1288
 
            ui.ui_factory.show_user_warning(
1289
 
                'deprecated_command',
1290
 
                deprecated_name=self.invoked_as,
1291
 
                recommended_name='branch',
1292
 
                deprecated_in_version='2.4')
1293
 
        accelerator_tree, br_from = controldir.ControlDir.open_tree_or_branch(
 
1169
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1294
1170
            from_location)
1295
1171
        if not (hardlink or files_from):
1296
1172
            # accelerator_tree is usually slower because you have to read N
1315
1191
            to_transport.mkdir('.')
1316
1192
        except errors.FileExists:
1317
1193
            if not use_existing_dir:
1318
 
                raise errors.BzrCommandError(gettext('Target directory "%s" '
1319
 
                    'already exists.') % to_location)
 
1194
                raise errors.BzrCommandError('Target directory "%s" '
 
1195
                    'already exists.' % to_location)
1320
1196
            else:
1321
1197
                try:
1322
 
                    to_dir = controldir.ControlDir.open_from_transport(
1323
 
                        to_transport)
 
1198
                    bzrdir.BzrDir.open_from_transport(to_transport)
1324
1199
                except errors.NotBranchError:
1325
 
                    to_dir = None
 
1200
                    pass
1326
1201
                else:
1327
 
                    try:
1328
 
                        to_dir.open_branch()
1329
 
                    except errors.NotBranchError:
1330
 
                        pass
1331
 
                    else:
1332
 
                        raise errors.AlreadyBranchError(to_location)
 
1202
                    raise errors.AlreadyBranchError(to_location)
1333
1203
        except errors.NoSuchFile:
1334
 
            raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
 
1204
            raise errors.BzrCommandError('Parent of "%s" does not exist.'
1335
1205
                                         % to_location)
1336
 
        else:
1337
 
            to_dir = None
1338
 
        if to_dir is None:
1339
 
            try:
1340
 
                # preserve whatever source format we have.
1341
 
                to_dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1342
 
                                            possible_transports=[to_transport],
1343
 
                                            accelerator_tree=accelerator_tree,
1344
 
                                            hardlink=hardlink, stacked=stacked,
1345
 
                                            force_new_repo=standalone,
1346
 
                                            create_tree_if_local=not no_tree,
1347
 
                                            source_branch=br_from)
1348
 
                branch = to_dir.open_branch()
1349
 
            except errors.NoSuchRevision:
1350
 
                to_transport.delete_tree('.')
1351
 
                msg = gettext("The branch {0} has no revision {1}.").format(
1352
 
                    from_location, revision)
1353
 
                raise errors.BzrCommandError(msg)
1354
 
        else:
1355
 
            branch = br_from.sprout(to_dir, revision_id=revision_id)
 
1206
        try:
 
1207
            # preserve whatever source format we have.
 
1208
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
1209
                                        possible_transports=[to_transport],
 
1210
                                        accelerator_tree=accelerator_tree,
 
1211
                                        hardlink=hardlink, stacked=stacked,
 
1212
                                        force_new_repo=standalone,
 
1213
                                        create_tree_if_local=not no_tree,
 
1214
                                        source_branch=br_from)
 
1215
            branch = dir.open_branch()
 
1216
        except errors.NoSuchRevision:
 
1217
            to_transport.delete_tree('.')
 
1218
            msg = "The branch %s has no revision %s." % (from_location,
 
1219
                revision)
 
1220
            raise errors.BzrCommandError(msg)
1356
1221
        _merge_tags_if_possible(br_from, branch)
1357
1222
        # If the source branch is stacked, the new branch may
1358
1223
        # be stacked whether we asked for that explicitly or not.
1359
1224
        # We therefore need a try/except here and not just 'if stacked:'
1360
1225
        try:
1361
 
            note(gettext('Created new stacked branch referring to %s.') %
 
1226
            note('Created new stacked branch referring to %s.' %
1362
1227
                branch.get_stacked_on_url())
1363
1228
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1364
1229
            errors.UnstackableRepositoryFormat), e:
1365
 
            note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
 
1230
            note('Branched %d revision(s).' % branch.revno())
1366
1231
        if bind:
1367
1232
            # Bind to the parent
1368
1233
            parent_branch = Branch.open(from_location)
1369
1234
            branch.bind(parent_branch)
1370
 
            note(gettext('New branch bound to %s') % from_location)
 
1235
            note('New branch bound to %s' % from_location)
1371
1236
        if switch:
1372
1237
            # Switch to the new branch
1373
1238
            wt, _ = WorkingTree.open_containing('.')
1374
1239
            _mod_switch.switch(wt.bzrdir, branch)
1375
 
            note(gettext('Switched to branch: %s'),
 
1240
            note('Switched to branch: %s',
1376
1241
                urlutils.unescape_for_display(branch.base, 'utf-8'))
1377
1242
 
1378
1243
 
1379
 
class cmd_branches(Command):
1380
 
    __doc__ = """List the branches available at the current location.
1381
 
 
1382
 
    This command will print the names of all the branches at the current
1383
 
    location.
1384
 
    """
1385
 
 
1386
 
    takes_args = ['location?']
1387
 
    takes_options = [
1388
 
                  Option('recursive', short_name='R',
1389
 
                         help='Recursively scan for branches rather than '
1390
 
                              'just looking in the specified location.')]
1391
 
 
1392
 
    def run(self, location=".", recursive=False):
1393
 
        if recursive:
1394
 
            t = transport.get_transport(location)
1395
 
            if not t.listable():
1396
 
                raise errors.BzrCommandError(
1397
 
                    "Can't scan this type of location.")
1398
 
            for b in controldir.ControlDir.find_branches(t):
1399
 
                self.outf.write("%s\n" % urlutils.unescape_for_display(
1400
 
                    urlutils.relative_url(t.base, b.base),
1401
 
                    self.outf.encoding).rstrip("/"))
1402
 
        else:
1403
 
            dir = controldir.ControlDir.open_containing(location)[0]
1404
 
            for branch in dir.list_branches():
1405
 
                if branch.name is None:
1406
 
                    self.outf.write(gettext(" (default)\n"))
1407
 
                else:
1408
 
                    self.outf.write(" %s\n" % branch.name.encode(
1409
 
                        self.outf.encoding))
1410
 
 
1411
 
 
1412
1244
class cmd_checkout(Command):
1413
1245
    __doc__ = """Create a new checkout of an existing branch.
1414
1246
 
1453
1285
        if branch_location is None:
1454
1286
            branch_location = osutils.getcwd()
1455
1287
            to_location = branch_location
1456
 
        accelerator_tree, source = controldir.ControlDir.open_tree_or_branch(
 
1288
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1457
1289
            branch_location)
1458
1290
        if not (hardlink or files_from):
1459
1291
            # accelerator_tree is usually slower because you have to read N
1514
1346
 
1515
1347
 
1516
1348
class cmd_update(Command):
1517
 
    __doc__ = """Update a working tree to a new revision.
1518
 
 
1519
 
    This will perform a merge of the destination revision (the tip of the
1520
 
    branch, or the specified revision) into the working tree, and then make
1521
 
    that revision the basis revision for the working tree.  
1522
 
 
1523
 
    You can use this to visit an older revision, or to update a working tree
1524
 
    that is out of date from its branch.
1525
 
    
1526
 
    If there are any uncommitted changes in the tree, they will be carried
1527
 
    across and remain as uncommitted changes after the update.  To discard
1528
 
    these changes, use 'bzr revert'.  The uncommitted changes may conflict
1529
 
    with the changes brought in by the change in basis revision.
1530
 
 
1531
 
    If the tree's branch is bound to a master branch, bzr will also update
 
1349
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1350
 
 
1351
    This will perform a merge into the working tree, and may generate
 
1352
    conflicts. If you have any local changes, you will still
 
1353
    need to commit them after the update for the update to be complete.
 
1354
 
 
1355
    If you want to discard your local changes, you can just do a
 
1356
    'bzr revert' instead of 'bzr commit' after the update.
 
1357
 
 
1358
    If the tree's branch is bound to a master branch, it will also update
1532
1359
    the branch from the master.
1533
 
 
1534
 
    You cannot update just a single file or directory, because each Bazaar
1535
 
    working tree has just a single basis revision.  If you want to restore a
1536
 
    file that has been removed locally, use 'bzr revert' instead of 'bzr
1537
 
    update'.  If you want to restore a file to its state in a previous
1538
 
    revision, use 'bzr revert' with a '-r' option, or use 'bzr cat' to write
1539
 
    out the old content of that file to a new location.
1540
 
 
1541
 
    The 'dir' argument, if given, must be the location of the root of a
1542
 
    working tree to update.  By default, the working tree that contains the 
1543
 
    current working directory is used.
1544
1360
    """
1545
1361
 
1546
1362
    _see_also = ['pull', 'working-trees', 'status-flags']
1547
1363
    takes_args = ['dir?']
1548
 
    takes_options = ['revision',
1549
 
                     Option('show-base',
1550
 
                            help="Show base revision text in conflicts."),
1551
 
                     ]
 
1364
    takes_options = ['revision']
1552
1365
    aliases = ['up']
1553
1366
 
1554
 
    def run(self, dir=None, revision=None, show_base=None):
 
1367
    def run(self, dir='.', revision=None):
1555
1368
        if revision is not None and len(revision) != 1:
1556
 
            raise errors.BzrCommandError(gettext(
1557
 
                "bzr update --revision takes exactly one revision"))
1558
 
        if dir is None:
1559
 
            tree = WorkingTree.open_containing('.')[0]
1560
 
        else:
1561
 
            tree, relpath = WorkingTree.open_containing(dir)
1562
 
            if relpath:
1563
 
                # See bug 557886.
1564
 
                raise errors.BzrCommandError(gettext(
1565
 
                    "bzr update can only update a whole tree, "
1566
 
                    "not a file or subdirectory"))
 
1369
            raise errors.BzrCommandError(
 
1370
                        "bzr update --revision takes exactly one revision")
 
1371
        tree = WorkingTree.open_containing(dir)[0]
1567
1372
        branch = tree.branch
1568
1373
        possible_transports = []
1569
1374
        master = branch.get_master_branch(
1593
1398
            revision_id = branch.last_revision()
1594
1399
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1595
1400
            revno = branch.revision_id_to_dotted_revno(revision_id)
1596
 
            note(gettext("Tree is up to date at revision {0} of branch {1}"
1597
 
                        ).format('.'.join(map(str, revno)), branch_location))
 
1401
            note("Tree is up to date at revision %s of branch %s" %
 
1402
                ('.'.join(map(str, revno)), branch_location))
1598
1403
            return 0
1599
1404
        view_info = _get_view_info_for_change_reporter(tree)
1600
1405
        change_reporter = delta._ChangeReporter(
1605
1410
                change_reporter,
1606
1411
                possible_transports=possible_transports,
1607
1412
                revision=revision_id,
1608
 
                old_tip=old_tip,
1609
 
                show_base=show_base)
 
1413
                old_tip=old_tip)
1610
1414
        except errors.NoSuchRevision, e:
1611
 
            raise errors.BzrCommandError(gettext(
 
1415
            raise errors.BzrCommandError(
1612
1416
                                  "branch has no revision %s\n"
1613
1417
                                  "bzr update --revision only works"
1614
 
                                  " for a revision in the branch history")
 
1418
                                  " for a revision in the branch history"
1615
1419
                                  % (e.revision))
1616
1420
        revno = tree.branch.revision_id_to_dotted_revno(
1617
1421
            _mod_revision.ensure_null(tree.last_revision()))
1618
 
        note(gettext('Updated to revision {0} of branch {1}').format(
1619
 
             '.'.join(map(str, revno)), branch_location))
 
1422
        note('Updated to revision %s of branch %s' %
 
1423
             ('.'.join(map(str, revno)), branch_location))
1620
1424
        parent_ids = tree.get_parent_ids()
1621
1425
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1622
 
            note(gettext('Your local commits will now show as pending merges with '
1623
 
                 "'bzr status', and can be committed with 'bzr commit'."))
 
1426
            note('Your local commits will now show as pending merges with '
 
1427
                 "'bzr status', and can be committed with 'bzr commit'.")
1624
1428
        if conflicts != 0:
1625
1429
            return 1
1626
1430
        else:
1667
1471
        else:
1668
1472
            noise_level = 0
1669
1473
        from bzrlib.info import show_bzrdir_info
1670
 
        show_bzrdir_info(controldir.ControlDir.open_containing(location)[0],
 
1474
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1671
1475
                         verbose=noise_level, outfile=self.outf)
1672
1476
 
1673
1477
 
1674
1478
class cmd_remove(Command):
1675
1479
    __doc__ = """Remove files or directories.
1676
1480
 
1677
 
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1678
 
    delete them if they can easily be recovered using revert otherwise they
1679
 
    will be backed up (adding an extention of the form .~#~). If no options or
1680
 
    parameters are given Bazaar will scan for files that are being tracked by
1681
 
    Bazaar but missing in your tree and stop tracking them for you.
 
1481
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1482
    them if they can easily be recovered using revert. If no options or
 
1483
    parameters are given bzr will scan for files that are being tracked by bzr
 
1484
    but missing in your tree and stop tracking them for you.
1682
1485
    """
1683
1486
    takes_args = ['file*']
1684
1487
    takes_options = ['verbose',
1686
1489
        RegistryOption.from_kwargs('file-deletion-strategy',
1687
1490
            'The file deletion mode to be used.',
1688
1491
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1689
 
            safe='Backup changed files (default).',
 
1492
            safe='Only delete files if they can be'
 
1493
                 ' safely recovered (default).',
1690
1494
            keep='Delete from bzr but leave the working copy.',
1691
 
            no_backup='Don\'t backup changed files.',
1692
1495
            force='Delete all the specified files, even if they can not be '
1693
 
                'recovered and even if they are non-empty directories. '
1694
 
                '(deprecated, use no-backup)')]
 
1496
                'recovered and even if they are non-empty directories.')]
1695
1497
    aliases = ['rm', 'del']
1696
1498
    encoding_type = 'replace'
1697
1499
 
1698
1500
    def run(self, file_list, verbose=False, new=False,
1699
1501
        file_deletion_strategy='safe'):
1700
 
        if file_deletion_strategy == 'force':
1701
 
            note(gettext("(The --force option is deprecated, rather use --no-backup "
1702
 
                "in future.)"))
1703
 
            file_deletion_strategy = 'no-backup'
1704
 
 
1705
1502
        tree, file_list = WorkingTree.open_containing_paths(file_list)
1706
1503
 
1707
1504
        if file_list is not None:
1715
1512
                specific_files=file_list).added
1716
1513
            file_list = sorted([f[0] for f in added], reverse=True)
1717
1514
            if len(file_list) == 0:
1718
 
                raise errors.BzrCommandError(gettext('No matching files.'))
 
1515
                raise errors.BzrCommandError('No matching files.')
1719
1516
        elif file_list is None:
1720
1517
            # missing files show up in iter_changes(basis) as
1721
1518
            # versioned-with-no-kind.
1728
1525
            file_deletion_strategy = 'keep'
1729
1526
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1730
1527
            keep_files=file_deletion_strategy=='keep',
1731
 
            force=(file_deletion_strategy=='no-backup'))
 
1528
            force=file_deletion_strategy=='force')
1732
1529
 
1733
1530
 
1734
1531
class cmd_file_id(Command):
1796
1593
 
1797
1594
    _see_also = ['check']
1798
1595
    takes_args = ['branch?']
1799
 
    takes_options = [
1800
 
        Option('canonicalize-chks',
1801
 
               help='Make sure CHKs are in canonical form (repairs '
1802
 
                    'bug 522637).',
1803
 
               hidden=True),
1804
 
        ]
1805
1596
 
1806
 
    def run(self, branch=".", canonicalize_chks=False):
 
1597
    def run(self, branch="."):
1807
1598
        from bzrlib.reconcile import reconcile
1808
 
        dir = controldir.ControlDir.open(branch)
1809
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1599
        dir = bzrdir.BzrDir.open(branch)
 
1600
        reconcile(dir)
1810
1601
 
1811
1602
 
1812
1603
class cmd_revision_history(Command):
1820
1611
    @display_command
1821
1612
    def run(self, location="."):
1822
1613
        branch = Branch.open_containing(location)[0]
1823
 
        self.add_cleanup(branch.lock_read().unlock)
1824
 
        graph = branch.repository.get_graph()
1825
 
        history = list(graph.iter_lefthand_ancestry(branch.last_revision(),
1826
 
            [_mod_revision.NULL_REVISION]))
1827
 
        for revid in reversed(history):
 
1614
        for revid in branch.revision_history():
1828
1615
            self.outf.write(revid)
1829
1616
            self.outf.write('\n')
1830
1617
 
1848
1635
            b = wt.branch
1849
1636
            last_revision = wt.last_revision()
1850
1637
 
1851
 
        self.add_cleanup(b.repository.lock_read().unlock)
1852
 
        graph = b.repository.get_graph()
1853
 
        revisions = [revid for revid, parents in
1854
 
            graph.iter_ancestry([last_revision])]
1855
 
        for revision_id in reversed(revisions):
1856
 
            if _mod_revision.is_null(revision_id):
1857
 
                continue
 
1638
        revision_ids = b.repository.get_ancestry(last_revision)
 
1639
        revision_ids.pop(0)
 
1640
        for revision_id in revision_ids:
1858
1641
            self.outf.write(revision_id + '\n')
1859
1642
 
1860
1643
 
1891
1674
                help='Specify a format for this branch. '
1892
1675
                'See "help formats".',
1893
1676
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1894
 
                converter=lambda name: controldir.format_registry.make_bzrdir(name),
 
1677
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1895
1678
                value_switches=True,
1896
1679
                title="Branch format",
1897
1680
                ),
1898
1681
         Option('append-revisions-only',
1899
1682
                help='Never change revnos or the existing log.'
1900
 
                '  Append revisions to it only.'),
1901
 
         Option('no-tree',
1902
 
                'Create a branch without a working tree.')
 
1683
                '  Append revisions to it only.')
1903
1684
         ]
1904
1685
    def run(self, location=None, format=None, append_revisions_only=False,
1905
 
            create_prefix=False, no_tree=False):
 
1686
            create_prefix=False):
1906
1687
        if format is None:
1907
 
            format = controldir.format_registry.make_bzrdir('default')
 
1688
            format = bzrdir.format_registry.make_bzrdir('default')
1908
1689
        if location is None:
1909
1690
            location = u'.'
1910
1691
 
1919
1700
            to_transport.ensure_base()
1920
1701
        except errors.NoSuchFile:
1921
1702
            if not create_prefix:
1922
 
                raise errors.BzrCommandError(gettext("Parent directory of %s"
 
1703
                raise errors.BzrCommandError("Parent directory of %s"
1923
1704
                    " does not exist."
1924
1705
                    "\nYou may supply --create-prefix to create all"
1925
 
                    " leading parent directories.")
 
1706
                    " leading parent directories."
1926
1707
                    % location)
1927
1708
            to_transport.create_prefix()
1928
1709
 
1929
1710
        try:
1930
 
            a_bzrdir = controldir.ControlDir.open_from_transport(to_transport)
 
1711
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1931
1712
        except errors.NotBranchError:
1932
1713
            # really a NotBzrDir error...
1933
 
            create_branch = controldir.ControlDir.create_branch_convenience
1934
 
            if no_tree:
1935
 
                force_new_tree = False
1936
 
            else:
1937
 
                force_new_tree = None
 
1714
            create_branch = bzrdir.BzrDir.create_branch_convenience
1938
1715
            branch = create_branch(to_transport.base, format=format,
1939
 
                                   possible_transports=[to_transport],
1940
 
                                   force_new_tree=force_new_tree)
 
1716
                                   possible_transports=[to_transport])
1941
1717
            a_bzrdir = branch.bzrdir
1942
1718
        else:
1943
1719
            from bzrlib.transport.local import LocalTransport
1947
1723
                        raise errors.BranchExistsWithoutWorkingTree(location)
1948
1724
                raise errors.AlreadyBranchError(location)
1949
1725
            branch = a_bzrdir.create_branch()
1950
 
            if not no_tree and not a_bzrdir.has_workingtree():
1951
 
                a_bzrdir.create_workingtree()
 
1726
            a_bzrdir.create_workingtree()
1952
1727
        if append_revisions_only:
1953
1728
            try:
1954
1729
                branch.set_append_revisions_only(True)
1955
1730
            except errors.UpgradeRequired:
1956
 
                raise errors.BzrCommandError(gettext('This branch format cannot be set'
1957
 
                    ' to append-revisions-only.  Try --default.'))
 
1731
                raise errors.BzrCommandError('This branch format cannot be set'
 
1732
                    ' to append-revisions-only.  Try --default.')
1958
1733
        if not is_quiet():
1959
1734
            from bzrlib.info import describe_layout, describe_format
1960
1735
            try:
1964
1739
            repository = branch.repository
1965
1740
            layout = describe_layout(repository, branch, tree).lower()
1966
1741
            format = describe_format(a_bzrdir, repository, branch, tree)
1967
 
            self.outf.write(gettext("Created a {0} (format: {1})\n").format(
1968
 
                  layout, format))
 
1742
            self.outf.write("Created a %s (format: %s)\n" % (layout, format))
1969
1743
            if repository.is_shared():
1970
1744
                #XXX: maybe this can be refactored into transport.path_or_url()
1971
1745
                url = repository.bzrdir.root_transport.external_url()
1973
1747
                    url = urlutils.local_path_from_url(url)
1974
1748
                except errors.InvalidURL:
1975
1749
                    pass
1976
 
                self.outf.write(gettext("Using shared repository: %s\n") % url)
 
1750
                self.outf.write("Using shared repository: %s\n" % url)
1977
1751
 
1978
1752
 
1979
1753
class cmd_init_repository(Command):
2009
1783
    takes_options = [RegistryOption('format',
2010
1784
                            help='Specify a format for this repository. See'
2011
1785
                                 ' "bzr help formats" for details.',
2012
 
                            lazy_registry=('bzrlib.controldir', 'format_registry'),
2013
 
                            converter=lambda name: controldir.format_registry.make_bzrdir(name),
 
1786
                            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1787
                            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2014
1788
                            value_switches=True, title='Repository format'),
2015
1789
                     Option('no-trees',
2016
1790
                             help='Branches in the repository will default to'
2020
1794
 
2021
1795
    def run(self, location, format=None, no_trees=False):
2022
1796
        if format is None:
2023
 
            format = controldir.format_registry.make_bzrdir('default')
 
1797
            format = bzrdir.format_registry.make_bzrdir('default')
2024
1798
 
2025
1799
        if location is None:
2026
1800
            location = '.'
2049
1823
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
2050
1824
    produces patches suitable for "patch -p1".
2051
1825
 
2052
 
    Note that when using the -r argument with a range of revisions, the
2053
 
    differences are computed between the two specified revisions.  That
2054
 
    is, the command does not show the changes introduced by the first 
2055
 
    revision in the range.  This differs from the interpretation of 
2056
 
    revision ranges used by "bzr log" which includes the first revision
2057
 
    in the range.
2058
 
 
2059
1826
    :Exit values:
2060
1827
        1 - changed
2061
1828
        2 - unrepresentable changes
2079
1846
 
2080
1847
            bzr diff -r1..3 xxx
2081
1848
 
2082
 
        The changes introduced by revision 2 (equivalent to -r1..2)::
2083
 
 
2084
 
            bzr diff -c2
2085
 
 
2086
 
        To see the changes introduced by revision X::
 
1849
        To see the changes introduced in revision X::
2087
1850
        
2088
1851
            bzr diff -cX
2089
1852
 
2093
1856
 
2094
1857
            bzr diff -r<chosen_parent>..X
2095
1858
 
2096
 
        The changes between the current revision and the previous revision
2097
 
        (equivalent to -c-1 and -r-2..-1)
 
1859
        The changes introduced by revision 2 (equivalent to -r1..2)::
2098
1860
 
2099
 
            bzr diff -r-2..
 
1861
            bzr diff -c2
2100
1862
 
2101
1863
        Show just the differences for file NEWS::
2102
1864
 
2117
1879
        Same as 'bzr diff' but prefix paths with old/ and new/::
2118
1880
 
2119
1881
            bzr diff --prefix old/:new/
2120
 
            
2121
 
        Show the differences using a custom diff program with options::
2122
 
        
2123
 
            bzr diff --using /usr/bin/diff --diff-options -wu
2124
1882
    """
2125
1883
    _see_also = ['status']
2126
1884
    takes_args = ['file*']
2127
1885
    takes_options = [
2128
1886
        Option('diff-options', type=str,
2129
 
               help='Pass these options to the external diff program.'),
 
1887
               help='Pass these options to the diff program.'),
2130
1888
        Option('prefix', type=str,
2131
1889
               short_name='p',
2132
1890
               help='Set prefixes added to old and new filenames, as '
2146
1904
            type=unicode,
2147
1905
            ),
2148
1906
        RegistryOption('format',
2149
 
            short_name='F',
2150
1907
            help='Diff format to use.',
2151
1908
            lazy_registry=('bzrlib.diff', 'format_registry'),
2152
 
            title='Diff format'),
 
1909
            value_switches=False, title='Diff format'),
2153
1910
        ]
2154
1911
    aliases = ['di', 'dif']
2155
1912
    encoding_type = 'exact'
2170
1927
        elif ':' in prefix:
2171
1928
            old_label, new_label = prefix.split(":")
2172
1929
        else:
2173
 
            raise errors.BzrCommandError(gettext(
 
1930
            raise errors.BzrCommandError(
2174
1931
                '--prefix expects two values separated by a colon'
2175
 
                ' (eg "old/:new/")'))
 
1932
                ' (eg "old/:new/")')
 
1933
 
 
1934
        if using is not None and diff_options is not None:
 
1935
            raise errors.BzrCommandError(
 
1936
            '--diff-options and --using are mutually exclusive.')
2176
1937
 
2177
1938
        if revision and len(revision) > 2:
2178
 
            raise errors.BzrCommandError(gettext('bzr diff --revision takes exactly'
2179
 
                                         ' one or two revision specifiers'))
 
1939
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
 
1940
                                         ' one or two revision specifiers')
2180
1941
 
2181
1942
        if using is not None and format is not None:
2182
 
            raise errors.BzrCommandError(gettext(
2183
 
                '{0} and {1} are mutually exclusive').format(
2184
 
                '--using', '--format'))
 
1943
            raise errors.BzrCommandError('--using and --format are mutually '
 
1944
                'exclusive.')
2185
1945
 
2186
1946
        (old_tree, new_tree,
2187
1947
         old_branch, new_branch,
2237
1997
    @display_command
2238
1998
    def run(self, null=False, directory=u'.'):
2239
1999
        tree = WorkingTree.open_containing(directory)[0]
2240
 
        self.add_cleanup(tree.lock_read().unlock)
2241
2000
        td = tree.changes_from(tree.basis_tree())
2242
 
        self.cleanup_now()
2243
2001
        for path, id, kind, text_modified, meta_modified in td.modified:
2244
2002
            if null:
2245
2003
                self.outf.write(path + '\0')
2264
2022
        basis_inv = basis.inventory
2265
2023
        inv = wt.inventory
2266
2024
        for file_id in inv:
2267
 
            if basis_inv.has_id(file_id):
 
2025
            if file_id in basis_inv:
2268
2026
                continue
2269
2027
            if inv.is_root(file_id) and len(basis_inv) == 0:
2270
2028
                continue
2295
2053
    try:
2296
2054
        return int(limitstring)
2297
2055
    except ValueError:
2298
 
        msg = gettext("The limit argument must be an integer.")
 
2056
        msg = "The limit argument must be an integer."
2299
2057
        raise errors.BzrCommandError(msg)
2300
2058
 
2301
2059
 
2303
2061
    try:
2304
2062
        return int(s)
2305
2063
    except ValueError:
2306
 
        msg = gettext("The levels argument must be an integer.")
 
2064
        msg = "The levels argument must be an integer."
2307
2065
        raise errors.BzrCommandError(msg)
2308
2066
 
2309
2067
 
2419
2177
 
2420
2178
    :Other filtering:
2421
2179
 
2422
 
      The --match option can be used for finding revisions that match a
2423
 
      regular expression in a commit message, committer, author or bug.
2424
 
      Specifying the option several times will match any of the supplied
2425
 
      expressions. --match-author, --match-bugs, --match-committer and
2426
 
      --match-message can be used to only match a specific field.
 
2180
      The --message option can be used for finding revisions that match a
 
2181
      regular expression in a commit message.
2427
2182
 
2428
2183
    :Tips & tricks:
2429
2184
 
2489
2244
                   argname='N',
2490
2245
                   type=_parse_levels),
2491
2246
            Option('message',
 
2247
                   short_name='m',
2492
2248
                   help='Show revisions whose message matches this '
2493
2249
                        'regular expression.',
2494
 
                   type=str,
2495
 
                   hidden=True),
 
2250
                   type=str),
2496
2251
            Option('limit',
2497
2252
                   short_name='l',
2498
2253
                   help='Limit the output to the first N revisions.',
2501
2256
            Option('show-diff',
2502
2257
                   short_name='p',
2503
2258
                   help='Show changes made in each revision as a patch.'),
2504
 
            Option('include-merged',
 
2259
            Option('include-merges',
2505
2260
                   help='Show merged revisions like --levels 0 does.'),
2506
 
            Option('include-merges', hidden=True,
2507
 
                   help='Historical alias for --include-merged.'),
2508
 
            Option('omit-merges',
2509
 
                   help='Do not report commits with more than one parent.'),
2510
2261
            Option('exclude-common-ancestry',
2511
2262
                   help='Display only the revisions that are not part'
2512
2263
                   ' of both ancestries (require -rX..Y)'
2513
 
                   ),
2514
 
            Option('signatures',
2515
 
                   help='Show digital signature validity'),
2516
 
            ListOption('match',
2517
 
                short_name='m',
2518
 
                help='Show revisions whose properties match this '
2519
 
                'expression.',
2520
 
                type=str),
2521
 
            ListOption('match-message',
2522
 
                   help='Show revisions whose message matches this '
2523
 
                   'expression.',
2524
 
                type=str),
2525
 
            ListOption('match-committer',
2526
 
                   help='Show revisions whose committer matches this '
2527
 
                   'expression.',
2528
 
                type=str),
2529
 
            ListOption('match-author',
2530
 
                   help='Show revisions whose authors match this '
2531
 
                   'expression.',
2532
 
                type=str),
2533
 
            ListOption('match-bugs',
2534
 
                   help='Show revisions whose bugs match this '
2535
 
                   'expression.',
2536
 
                type=str)
 
2264
                   )
2537
2265
            ]
2538
2266
    encoding_type = 'replace'
2539
2267
 
2549
2277
            message=None,
2550
2278
            limit=None,
2551
2279
            show_diff=False,
2552
 
            include_merged=None,
 
2280
            include_merges=False,
2553
2281
            authors=None,
2554
2282
            exclude_common_ancestry=False,
2555
 
            signatures=False,
2556
 
            match=None,
2557
 
            match_message=None,
2558
 
            match_committer=None,
2559
 
            match_author=None,
2560
 
            match_bugs=None,
2561
 
            omit_merges=False,
2562
 
            include_merges=symbol_versioning.DEPRECATED_PARAMETER,
2563
2283
            ):
2564
2284
        from bzrlib.log import (
2565
2285
            Logger,
2567
2287
            _get_info_for_log_files,
2568
2288
            )
2569
2289
        direction = (forward and 'forward') or 'reverse'
2570
 
        if symbol_versioning.deprecated_passed(include_merges):
2571
 
            ui.ui_factory.show_user_warning(
2572
 
                'deprecated_command_option',
2573
 
                deprecated_name='--include-merges',
2574
 
                recommended_name='--include-merged',
2575
 
                deprecated_in_version='2.5',
2576
 
                command=self.invoked_as)
2577
 
            if include_merged is None:
2578
 
                include_merged = include_merges
2579
 
            else:
2580
 
                raise errors.BzrCommandError(gettext(
2581
 
                    '{0} and {1} are mutually exclusive').format(
2582
 
                    '--include-merges', '--include-merged'))
2583
 
        if include_merged is None:
2584
 
            include_merged = False
2585
2290
        if (exclude_common_ancestry
2586
2291
            and (revision is None or len(revision) != 2)):
2587
 
            raise errors.BzrCommandError(gettext(
2588
 
                '--exclude-common-ancestry requires -r with two revisions'))
2589
 
        if include_merged:
 
2292
            raise errors.BzrCommandError(
 
2293
                '--exclude-common-ancestry requires -r with two revisions')
 
2294
        if include_merges:
2590
2295
            if levels is None:
2591
2296
                levels = 0
2592
2297
            else:
2593
 
                raise errors.BzrCommandError(gettext(
2594
 
                    '{0} and {1} are mutually exclusive').format(
2595
 
                    '--levels', '--include-merged'))
 
2298
                raise errors.BzrCommandError(
 
2299
                    '--levels and --include-merges are mutually exclusive')
2596
2300
 
2597
2301
        if change is not None:
2598
2302
            if len(change) > 1:
2599
2303
                raise errors.RangeInChangeOption()
2600
2304
            if revision is not None:
2601
 
                raise errors.BzrCommandError(gettext(
2602
 
                    '{0} and {1} are mutually exclusive').format(
2603
 
                    '--revision', '--change'))
 
2305
                raise errors.BzrCommandError(
 
2306
                    '--revision and --change are mutually exclusive')
2604
2307
            else:
2605
2308
                revision = change
2606
2309
 
2612
2315
                revision, file_list, self.add_cleanup)
2613
2316
            for relpath, file_id, kind in file_info_list:
2614
2317
                if file_id is None:
2615
 
                    raise errors.BzrCommandError(gettext(
2616
 
                        "Path unknown at end or start of revision range: %s") %
 
2318
                    raise errors.BzrCommandError(
 
2319
                        "Path unknown at end or start of revision range: %s" %
2617
2320
                        relpath)
2618
2321
                # If the relpath is the top of the tree, we log everything
2619
2322
                if relpath == '':
2631
2334
                location = revision[0].get_branch()
2632
2335
            else:
2633
2336
                location = '.'
2634
 
            dir, relpath = controldir.ControlDir.open_containing(location)
 
2337
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2635
2338
            b = dir.open_branch()
2636
2339
            self.add_cleanup(b.lock_read().unlock)
2637
2340
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2638
2341
 
2639
 
        if b.get_config().validate_signatures_in_log():
2640
 
            signatures = True
2641
 
 
2642
 
        if signatures:
2643
 
            if not gpg.GPGStrategy.verify_signatures_available():
2644
 
                raise errors.GpgmeNotInstalled(None)
2645
 
 
2646
2342
        # Decide on the type of delta & diff filtering to use
2647
2343
        # TODO: add an --all-files option to make this configurable & consistent
2648
2344
        if not verbose:
2685
2381
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2686
2382
            or delta_type or partial_history)
2687
2383
 
2688
 
        match_dict = {}
2689
 
        if match:
2690
 
            match_dict[''] = match
2691
 
        if match_message:
2692
 
            match_dict['message'] = match_message
2693
 
        if match_committer:
2694
 
            match_dict['committer'] = match_committer
2695
 
        if match_author:
2696
 
            match_dict['author'] = match_author
2697
 
        if match_bugs:
2698
 
            match_dict['bugs'] = match_bugs
2699
 
 
2700
2384
        # Build the LogRequest and execute it
2701
2385
        if len(file_ids) == 0:
2702
2386
            file_ids = None
2705
2389
            start_revision=rev1, end_revision=rev2, limit=limit,
2706
2390
            message_search=message, delta_type=delta_type,
2707
2391
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2708
 
            exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
2709
 
            signature=signatures, omit_merges=omit_merges,
 
2392
            exclude_common_ancestry=exclude_common_ancestry,
2710
2393
            )
2711
2394
        Logger(b, rqst).show(lf)
2712
2395
 
2729
2412
            # b is taken from revision[0].get_branch(), and
2730
2413
            # show_log will use its revision_history. Having
2731
2414
            # different branches will lead to weird behaviors.
2732
 
            raise errors.BzrCommandError(gettext(
 
2415
            raise errors.BzrCommandError(
2733
2416
                "bzr %s doesn't accept two revisions in different"
2734
 
                " branches.") % command_name)
 
2417
                " branches." % command_name)
2735
2418
        if start_spec.spec is None:
2736
2419
            # Avoid loading all the history.
2737
2420
            rev1 = RevisionInfo(branch, None, None)
2745
2428
        else:
2746
2429
            rev2 = end_spec.in_history(branch)
2747
2430
    else:
2748
 
        raise errors.BzrCommandError(gettext(
2749
 
            'bzr %s --revision takes one or two values.') % command_name)
 
2431
        raise errors.BzrCommandError(
 
2432
            'bzr %s --revision takes one or two values.' % command_name)
2750
2433
    return rev1, rev2
2751
2434
 
2752
2435
 
2823
2506
            null=False, kind=None, show_ids=False, path=None, directory=None):
2824
2507
 
2825
2508
        if kind and kind not in ('file', 'directory', 'symlink'):
2826
 
            raise errors.BzrCommandError(gettext('invalid kind specified'))
 
2509
            raise errors.BzrCommandError('invalid kind specified')
2827
2510
 
2828
2511
        if verbose and null:
2829
 
            raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
 
2512
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
2830
2513
        all = not (unknown or versioned or ignored)
2831
2514
 
2832
2515
        selection = {'I':ignored, '?':unknown, 'V':versioned}
2835
2518
            fs_path = '.'
2836
2519
        else:
2837
2520
            if from_root:
2838
 
                raise errors.BzrCommandError(gettext('cannot specify both --from-root'
2839
 
                                             ' and PATH'))
 
2521
                raise errors.BzrCommandError('cannot specify both --from-root'
 
2522
                                             ' and PATH')
2840
2523
            fs_path = path
2841
2524
        tree, branch, relpath = \
2842
2525
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
2858
2541
            if view_files:
2859
2542
                apply_view = True
2860
2543
                view_str = views.view_display_str(view_files)
2861
 
                note(gettext("Ignoring files outside view. View is %s") % view_str)
 
2544
                note("Ignoring files outside view. View is %s" % view_str)
2862
2545
 
2863
2546
        self.add_cleanup(tree.lock_read().unlock)
2864
2547
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2950
2633
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2951
2634
    precedence over the '!' exception patterns.
2952
2635
 
2953
 
    :Notes: 
2954
 
        
2955
 
    * Ignore patterns containing shell wildcards must be quoted from
2956
 
      the shell on Unix.
2957
 
 
2958
 
    * Ignore patterns starting with "#" act as comments in the ignore file.
2959
 
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
2636
    Note: ignore patterns containing shell wildcards must be quoted from
 
2637
    the shell on Unix.
2960
2638
 
2961
2639
    :Examples:
2962
2640
        Ignore the top level Makefile::
2971
2649
 
2972
2650
            bzr ignore "!special.class"
2973
2651
 
2974
 
        Ignore files whose name begins with the "#" character::
2975
 
 
2976
 
            bzr ignore "RE:^#"
2977
 
 
2978
2652
        Ignore .o files under the lib directory::
2979
2653
 
2980
2654
            bzr ignore "lib/**/*.o"
2988
2662
            bzr ignore "RE:(?!debian/).*"
2989
2663
        
2990
2664
        Ignore everything except the "local" toplevel directory,
2991
 
        but always ignore autosave files ending in ~, even under local/::
 
2665
        but always ignore "*~" autosave files, even under local/::
2992
2666
        
2993
2667
            bzr ignore "*"
2994
2668
            bzr ignore "!./local"
3011
2685
                self.outf.write("%s\n" % pattern)
3012
2686
            return
3013
2687
        if not name_pattern_list:
3014
 
            raise errors.BzrCommandError(gettext("ignore requires at least one "
3015
 
                "NAME_PATTERN or --default-rules."))
 
2688
            raise errors.BzrCommandError("ignore requires at least one "
 
2689
                "NAME_PATTERN or --default-rules.")
3016
2690
        name_pattern_list = [globbing.normalize_pattern(p)
3017
2691
                             for p in name_pattern_list]
3018
 
        bad_patterns = ''
3019
 
        bad_patterns_count = 0
3020
 
        for p in name_pattern_list:
3021
 
            if not globbing.Globster.is_pattern_valid(p):
3022
 
                bad_patterns_count += 1
3023
 
                bad_patterns += ('\n  %s' % p)
3024
 
        if bad_patterns:
3025
 
            msg = (ngettext('Invalid ignore pattern found. %s', 
3026
 
                            'Invalid ignore patterns found. %s',
3027
 
                            bad_patterns_count) % bad_patterns)
3028
 
            ui.ui_factory.show_error(msg)
3029
 
            raise errors.InvalidPattern('')
3030
2692
        for name_pattern in name_pattern_list:
3031
2693
            if (name_pattern[0] == '/' or
3032
2694
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
3033
 
                raise errors.BzrCommandError(gettext(
3034
 
                    "NAME_PATTERN should not be an absolute path"))
 
2695
                raise errors.BzrCommandError(
 
2696
                    "NAME_PATTERN should not be an absolute path")
3035
2697
        tree, relpath = WorkingTree.open_containing(directory)
3036
2698
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
3037
2699
        ignored = globbing.Globster(name_pattern_list)
3044
2706
                if ignored.match(filename):
3045
2707
                    matches.append(filename)
3046
2708
        if len(matches) > 0:
3047
 
            self.outf.write(gettext("Warning: the following files are version "
3048
 
                  "controlled and match your ignore pattern:\n%s"
 
2709
            self.outf.write("Warning: the following files are version controlled and"
 
2710
                  " match your ignore pattern:\n%s"
3049
2711
                  "\nThese files will continue to be version controlled"
3050
 
                  " unless you 'bzr remove' them.\n") % ("\n".join(matches),))
 
2712
                  " unless you 'bzr remove' them.\n" % ("\n".join(matches),))
3051
2713
 
3052
2714
 
3053
2715
class cmd_ignored(Command):
3092
2754
        try:
3093
2755
            revno = int(revno)
3094
2756
        except ValueError:
3095
 
            raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
 
2757
            raise errors.BzrCommandError("not a valid revision-number: %r"
3096
2758
                                         % revno)
3097
2759
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
3098
2760
        self.outf.write("%s\n" % revid)
3126
2788
         zip                          .zip
3127
2789
      =================       =========================
3128
2790
    """
3129
 
    encoding = 'exact'
3130
2791
    takes_args = ['dest', 'branch_or_subdir?']
3131
2792
    takes_options = ['directory',
3132
2793
        Option('format',
3159
2820
            export(rev_tree, dest, format, root, subdir, filtered=filters,
3160
2821
                   per_file_timestamps=per_file_timestamps)
3161
2822
        except errors.NoSuchExportFormat, e:
3162
 
            raise errors.BzrCommandError(gettext('Unsupported export format: %s') % e.format)
 
2823
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3163
2824
 
3164
2825
 
3165
2826
class cmd_cat(Command):
3185
2846
    def run(self, filename, revision=None, name_from_revision=False,
3186
2847
            filters=False, directory=None):
3187
2848
        if revision is not None and len(revision) != 1:
3188
 
            raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3189
 
                                         " one revision specifier"))
 
2849
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
 
2850
                                         " one revision specifier")
3190
2851
        tree, branch, relpath = \
3191
2852
            _open_directory_or_containing_tree_or_branch(filename, directory)
3192
2853
        self.add_cleanup(branch.lock_read().unlock)
3202
2863
 
3203
2864
        old_file_id = rev_tree.path2id(relpath)
3204
2865
 
3205
 
        # TODO: Split out this code to something that generically finds the
3206
 
        # best id for a path across one or more trees; it's like
3207
 
        # find_ids_across_trees but restricted to find just one. -- mbp
3208
 
        # 20110705.
3209
2866
        if name_from_revision:
3210
2867
            # Try in revision if requested
3211
2868
            if old_file_id is None:
3212
 
                raise errors.BzrCommandError(gettext(
3213
 
                    "{0!r} is not present in revision {1}").format(
 
2869
                raise errors.BzrCommandError(
 
2870
                    "%r is not present in revision %s" % (
3214
2871
                        filename, rev_tree.get_revision_id()))
3215
2872
            else:
3216
 
                actual_file_id = old_file_id
 
2873
                content = rev_tree.get_file_text(old_file_id)
3217
2874
        else:
3218
2875
            cur_file_id = tree.path2id(relpath)
3219
 
            if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3220
 
                actual_file_id = cur_file_id
3221
 
            elif old_file_id is not None:
3222
 
                actual_file_id = old_file_id
3223
 
            else:
3224
 
                raise errors.BzrCommandError(gettext(
3225
 
                    "{0!r} is not present in revision {1}").format(
 
2876
            found = False
 
2877
            if cur_file_id is not None:
 
2878
                # Then try with the actual file id
 
2879
                try:
 
2880
                    content = rev_tree.get_file_text(cur_file_id)
 
2881
                    found = True
 
2882
                except errors.NoSuchId:
 
2883
                    # The actual file id didn't exist at that time
 
2884
                    pass
 
2885
            if not found and old_file_id is not None:
 
2886
                # Finally try with the old file id
 
2887
                content = rev_tree.get_file_text(old_file_id)
 
2888
                found = True
 
2889
            if not found:
 
2890
                # Can't be found anywhere
 
2891
                raise errors.BzrCommandError(
 
2892
                    "%r is not present in revision %s" % (
3226
2893
                        filename, rev_tree.get_revision_id()))
3227
2894
        if filtered:
3228
 
            from bzrlib.filter_tree import ContentFilterTree
3229
 
            filter_tree = ContentFilterTree(rev_tree,
3230
 
                rev_tree._content_filter_stack)
3231
 
            content = filter_tree.get_file_text(actual_file_id)
 
2895
            from bzrlib.filters import (
 
2896
                ContentFilterContext,
 
2897
                filtered_output_bytes,
 
2898
                )
 
2899
            filters = rev_tree._content_filter_stack(relpath)
 
2900
            chunks = content.splitlines(True)
 
2901
            content = filtered_output_bytes(chunks, filters,
 
2902
                ContentFilterContext(relpath, rev_tree))
 
2903
            self.cleanup_now()
 
2904
            self.outf.writelines(content)
3232
2905
        else:
3233
 
            content = rev_tree.get_file_text(actual_file_id)
3234
 
        self.cleanup_now()
3235
 
        self.outf.write(content)
 
2906
            self.cleanup_now()
 
2907
            self.outf.write(content)
3236
2908
 
3237
2909
 
3238
2910
class cmd_local_time_offset(Command):
3299
2971
      to trigger updates to external systems like bug trackers. The --fixes
3300
2972
      option can be used to record the association between a revision and
3301
2973
      one or more bugs. See ``bzr help bugs`` for details.
 
2974
 
 
2975
      A selective commit may fail in some cases where the committed
 
2976
      tree would be invalid. Consider::
 
2977
  
 
2978
        bzr init foo
 
2979
        mkdir foo/bar
 
2980
        bzr add foo/bar
 
2981
        bzr commit foo -m "committing foo"
 
2982
        bzr mv foo/bar foo/baz
 
2983
        mkdir foo/bar
 
2984
        bzr add foo/bar
 
2985
        bzr commit foo/bar -m "committing bar but not baz"
 
2986
  
 
2987
      In the example above, the last commit will fail by design. This gives
 
2988
      the user the opportunity to decide whether they want to commit the
 
2989
      rename at the same time, separately first, or not at all. (As a general
 
2990
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
3302
2991
    """
 
2992
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
2993
 
 
2994
    # TODO: Strict commit that fails if there are deleted files.
 
2995
    #       (what does "deleted files" mean ??)
 
2996
 
 
2997
    # TODO: Give better message for -s, --summary, used by tla people
 
2998
 
 
2999
    # XXX: verbose currently does nothing
3303
3000
 
3304
3001
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
3305
3002
    takes_args = ['selected*']
3337
3034
             Option('show-diff', short_name='p',
3338
3035
                    help='When no message is supplied, show the diff along'
3339
3036
                    ' with the status summary in the message editor.'),
3340
 
             Option('lossy', 
3341
 
                    help='When committing to a foreign version control '
3342
 
                    'system do not push data that can not be natively '
3343
 
                    'represented.'),
3344
3037
             ]
3345
3038
    aliases = ['ci', 'checkin']
3346
3039
 
3347
3040
    def _iter_bug_fix_urls(self, fixes, branch):
3348
 
        default_bugtracker  = None
3349
3041
        # Configure the properties for bug fixing attributes.
3350
3042
        for fixed_bug in fixes:
3351
3043
            tokens = fixed_bug.split(':')
3352
 
            if len(tokens) == 1:
3353
 
                if default_bugtracker is None:
3354
 
                    branch_config = branch.get_config()
3355
 
                    default_bugtracker = branch_config.get_user_option(
3356
 
                        "bugtracker")
3357
 
                if default_bugtracker is None:
3358
 
                    raise errors.BzrCommandError(gettext(
3359
 
                        "No tracker specified for bug %s. Use the form "
3360
 
                        "'tracker:id' or specify a default bug tracker "
3361
 
                        "using the `bugtracker` option.\nSee "
3362
 
                        "\"bzr help bugs\" for more information on this "
3363
 
                        "feature. Commit refused.") % fixed_bug)
3364
 
                tag = default_bugtracker
3365
 
                bug_id = tokens[0]
3366
 
            elif len(tokens) != 2:
3367
 
                raise errors.BzrCommandError(gettext(
 
3044
            if len(tokens) != 2:
 
3045
                raise errors.BzrCommandError(
3368
3046
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
3369
3047
                    "See \"bzr help bugs\" for more information on this "
3370
 
                    "feature.\nCommit refused.") % fixed_bug)
3371
 
            else:
3372
 
                tag, bug_id = tokens
 
3048
                    "feature.\nCommit refused." % fixed_bug)
 
3049
            tag, bug_id = tokens
3373
3050
            try:
3374
3051
                yield bugtracker.get_bug_url(tag, branch, bug_id)
3375
3052
            except errors.UnknownBugTrackerAbbreviation:
3376
 
                raise errors.BzrCommandError(gettext(
3377
 
                    'Unrecognized bug %s. Commit refused.') % fixed_bug)
 
3053
                raise errors.BzrCommandError(
 
3054
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
3378
3055
            except errors.MalformedBugIdentifier, e:
3379
 
                raise errors.BzrCommandError(gettext(
3380
 
                    "%s\nCommit refused.") % (str(e),))
 
3056
                raise errors.BzrCommandError(
 
3057
                    "%s\nCommit refused." % (str(e),))
3381
3058
 
3382
3059
    def run(self, message=None, file=None, verbose=False, selected_list=None,
3383
3060
            unchanged=False, strict=False, local=False, fixes=None,
3384
 
            author=None, show_diff=False, exclude=None, commit_time=None,
3385
 
            lossy=False):
 
3061
            author=None, show_diff=False, exclude=None, commit_time=None):
3386
3062
        from bzrlib.errors import (
3387
3063
            PointlessCommit,
3388
3064
            ConflictsInTree,
3391
3067
        from bzrlib.msgeditor import (
3392
3068
            edit_commit_message_encoded,
3393
3069
            generate_commit_message_template,
3394
 
            make_commit_message_template_encoded,
3395
 
            set_commit_message,
 
3070
            make_commit_message_template_encoded
3396
3071
        )
3397
3072
 
3398
3073
        commit_stamp = offset = None
3400
3075
            try:
3401
3076
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3402
3077
            except ValueError, e:
3403
 
                raise errors.BzrCommandError(gettext(
3404
 
                    "Could not parse --commit-time: " + str(e)))
 
3078
                raise errors.BzrCommandError(
 
3079
                    "Could not parse --commit-time: " + str(e))
 
3080
 
 
3081
        # TODO: Need a blackbox test for invoking the external editor; may be
 
3082
        # slightly problematic to run this cross-platform.
 
3083
 
 
3084
        # TODO: do more checks that the commit will succeed before
 
3085
        # spending the user's valuable time typing a commit message.
3405
3086
 
3406
3087
        properties = {}
3407
3088
 
3440
3121
                message = message.replace('\r\n', '\n')
3441
3122
                message = message.replace('\r', '\n')
3442
3123
            if file:
3443
 
                raise errors.BzrCommandError(gettext(
3444
 
                    "please specify either --message or --file"))
 
3124
                raise errors.BzrCommandError(
 
3125
                    "please specify either --message or --file")
3445
3126
 
3446
3127
        def get_message(commit_obj):
3447
3128
            """Callback to get commit message"""
3448
3129
            if file:
3449
 
                f = open(file)
 
3130
                f = codecs.open(file, 'rt', osutils.get_user_encoding())
3450
3131
                try:
3451
 
                    my_message = f.read().decode(osutils.get_user_encoding())
 
3132
                    my_message = f.read()
3452
3133
                finally:
3453
3134
                    f.close()
3454
3135
            elif message is not None:
3464
3145
                # make_commit_message_template_encoded returns user encoding.
3465
3146
                # We probably want to be using edit_commit_message instead to
3466
3147
                # avoid this.
3467
 
                my_message = set_commit_message(commit_obj)
3468
 
                if my_message is None:
3469
 
                    start_message = generate_commit_message_template(commit_obj)
3470
 
                    my_message = edit_commit_message_encoded(text,
3471
 
                        start_message=start_message)
3472
 
                if my_message is None:
3473
 
                    raise errors.BzrCommandError(gettext("please specify a commit"
3474
 
                        " message with either --message or --file"))
3475
 
                if my_message == "":
3476
 
                    raise errors.BzrCommandError(gettext("Empty commit message specified."
3477
 
                            " Please specify a commit message with either"
3478
 
                            " --message or --file or leave a blank message"
3479
 
                            " with --message \"\"."))
 
3148
                start_message = generate_commit_message_template(commit_obj)
 
3149
                my_message = edit_commit_message_encoded(text,
 
3150
                    start_message=start_message)
 
3151
                if my_message is None:
 
3152
                    raise errors.BzrCommandError("please specify a commit"
 
3153
                        " message with either --message or --file")
 
3154
            if my_message == "":
 
3155
                raise errors.BzrCommandError("empty commit message specified")
3480
3156
            return my_message
3481
3157
 
3482
3158
        # The API permits a commit with a filter of [] to mean 'select nothing'
3490
3166
                        reporter=None, verbose=verbose, revprops=properties,
3491
3167
                        authors=author, timestamp=commit_stamp,
3492
3168
                        timezone=offset,
3493
 
                        exclude=tree.safe_relpath_files(exclude),
3494
 
                        lossy=lossy)
 
3169
                        exclude=tree.safe_relpath_files(exclude))
3495
3170
        except PointlessCommit:
3496
 
            raise errors.BzrCommandError(gettext("No changes to commit."
3497
 
                " Please 'bzr add' the files you want to commit, or use"
3498
 
                " --unchanged to force an empty commit."))
 
3171
            raise errors.BzrCommandError("No changes to commit."
 
3172
                              " Use --unchanged to commit anyhow.")
3499
3173
        except ConflictsInTree:
3500
 
            raise errors.BzrCommandError(gettext('Conflicts detected in working '
 
3174
            raise errors.BzrCommandError('Conflicts detected in working '
3501
3175
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3502
 
                ' resolve.'))
 
3176
                ' resolve.')
3503
3177
        except StrictCommitFailed:
3504
 
            raise errors.BzrCommandError(gettext("Commit refused because there are"
3505
 
                              " unknown files in the working tree."))
 
3178
            raise errors.BzrCommandError("Commit refused because there are"
 
3179
                              " unknown files in the working tree.")
3506
3180
        except errors.BoundBranchOutOfDate, e:
3507
 
            e.extra_help = (gettext("\n"
 
3181
            e.extra_help = ("\n"
3508
3182
                'To commit to master branch, run update and then commit.\n'
3509
3183
                'You can also pass --local to commit to continue working '
3510
 
                'disconnected.'))
 
3184
                'disconnected.')
3511
3185
            raise
3512
3186
 
3513
3187
 
3582
3256
 
3583
3257
 
3584
3258
class cmd_upgrade(Command):
3585
 
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
3586
 
 
3587
 
    When the default format has changed after a major new release of
3588
 
    Bazaar, you may be informed during certain operations that you
3589
 
    should upgrade. Upgrading to a newer format may improve performance
3590
 
    or make new features available. It may however limit interoperability
3591
 
    with older repositories or with older versions of Bazaar.
3592
 
 
3593
 
    If you wish to upgrade to a particular format rather than the
3594
 
    current default, that can be specified using the --format option.
3595
 
    As a consequence, you can use the upgrade command this way to
3596
 
    "downgrade" to an earlier format, though some conversions are
3597
 
    a one way process (e.g. changing from the 1.x default to the
3598
 
    2.x default) so downgrading is not always possible.
3599
 
 
3600
 
    A backup.bzr.~#~ directory is created at the start of the conversion
3601
 
    process (where # is a number). By default, this is left there on
3602
 
    completion. If the conversion fails, delete the new .bzr directory
3603
 
    and rename this one back in its place. Use the --clean option to ask
3604
 
    for the backup.bzr directory to be removed on successful conversion.
3605
 
    Alternatively, you can delete it by hand if everything looks good
3606
 
    afterwards.
3607
 
 
3608
 
    If the location given is a shared repository, dependent branches
3609
 
    are also converted provided the repository converts successfully.
3610
 
    If the conversion of a branch fails, remaining branches are still
3611
 
    tried.
3612
 
 
3613
 
    For more information on upgrades, see the Bazaar Upgrade Guide,
3614
 
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
 
3259
    __doc__ = """Upgrade branch storage to current format.
 
3260
 
 
3261
    The check command or bzr developers may sometimes advise you to run
 
3262
    this command. When the default format has changed you may also be warned
 
3263
    during other operations to upgrade.
3615
3264
    """
3616
3265
 
3617
 
    _see_also = ['check', 'reconcile', 'formats']
 
3266
    _see_also = ['check']
3618
3267
    takes_args = ['url?']
3619
3268
    takes_options = [
3620
 
        RegistryOption('format',
3621
 
            help='Upgrade to a specific format.  See "bzr help'
3622
 
                 ' formats" for details.',
3623
 
            lazy_registry=('bzrlib.controldir', 'format_registry'),
3624
 
            converter=lambda name: controldir.format_registry.make_bzrdir(name),
3625
 
            value_switches=True, title='Branch format'),
3626
 
        Option('clean',
3627
 
            help='Remove the backup.bzr directory if successful.'),
3628
 
        Option('dry-run',
3629
 
            help="Show what would be done, but don't actually do anything."),
3630
 
    ]
 
3269
                    RegistryOption('format',
 
3270
                        help='Upgrade to a specific format.  See "bzr help'
 
3271
                             ' formats" for details.',
 
3272
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3273
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
 
3274
                        value_switches=True, title='Branch format'),
 
3275
                    ]
3631
3276
 
3632
 
    def run(self, url='.', format=None, clean=False, dry_run=False):
 
3277
    def run(self, url='.', format=None):
3633
3278
        from bzrlib.upgrade import upgrade
3634
 
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3635
 
        if exceptions:
3636
 
            if len(exceptions) == 1:
3637
 
                # Compatibility with historical behavior
3638
 
                raise exceptions[0]
3639
 
            else:
3640
 
                return 3
 
3279
        upgrade(url, format)
3641
3280
 
3642
3281
 
3643
3282
class cmd_whoami(Command):
3670
3309
                try:
3671
3310
                    c = Branch.open_containing(u'.')[0].get_config()
3672
3311
                except errors.NotBranchError:
3673
 
                    c = _mod_config.GlobalConfig()
 
3312
                    c = config.GlobalConfig()
3674
3313
            else:
3675
3314
                c = Branch.open(directory).get_config()
3676
3315
            if email:
3679
3318
                self.outf.write(c.username() + '\n')
3680
3319
            return
3681
3320
 
3682
 
        if email:
3683
 
            raise errors.BzrCommandError(gettext("--email can only be used to display existing "
3684
 
                                         "identity"))
3685
 
 
3686
3321
        # display a warning if an email address isn't included in the given name.
3687
3322
        try:
3688
 
            _mod_config.extract_email_address(name)
 
3323
            config.extract_email_address(name)
3689
3324
        except errors.NoEmailInUsername, e:
3690
3325
            warning('"%s" does not seem to contain an email address.  '
3691
3326
                    'This is allowed, but not recommended.', name)
3697
3332
            else:
3698
3333
                c = Branch.open(directory).get_config()
3699
3334
        else:
3700
 
            c = _mod_config.GlobalConfig()
 
3335
            c = config.GlobalConfig()
3701
3336
        c.set_user_option('email', name)
3702
3337
 
3703
3338
 
3766
3401
 
3767
3402
    def remove_alias(self, alias_name):
3768
3403
        if alias_name is None:
3769
 
            raise errors.BzrCommandError(gettext(
3770
 
                'bzr alias --remove expects an alias to remove.'))
 
3404
            raise errors.BzrCommandError(
 
3405
                'bzr alias --remove expects an alias to remove.')
3771
3406
        # If alias is not found, print something like:
3772
3407
        # unalias: foo: not found
3773
 
        c = _mod_config.GlobalConfig()
 
3408
        c = config.GlobalConfig()
3774
3409
        c.unset_alias(alias_name)
3775
3410
 
3776
3411
    @display_command
3777
3412
    def print_aliases(self):
3778
3413
        """Print out the defined aliases in a similar format to bash."""
3779
 
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3414
        aliases = config.GlobalConfig().get_aliases()
3780
3415
        for key, value in sorted(aliases.iteritems()):
3781
3416
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3782
3417
 
3792
3427
 
3793
3428
    def set_alias(self, alias_name, alias_command):
3794
3429
        """Save the alias in the global config."""
3795
 
        c = _mod_config.GlobalConfig()
 
3430
        c = config.GlobalConfig()
3796
3431
        c.set_alias(alias_name, alias_command)
3797
3432
 
3798
3433
 
3833
3468
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3834
3469
    into a pdb postmortem session.
3835
3470
 
3836
 
    The --coverage=DIRNAME global option produces a report with covered code
3837
 
    indicated.
3838
 
 
3839
3471
    :Examples:
3840
3472
        Run only tests relating to 'ignore'::
3841
3473
 
3852
3484
        if typestring == "sftp":
3853
3485
            from bzrlib.tests import stub_sftp
3854
3486
            return stub_sftp.SFTPAbsoluteServer
3855
 
        elif typestring == "memory":
 
3487
        if typestring == "memory":
3856
3488
            from bzrlib.tests import test_server
3857
3489
            return memory.MemoryServer
3858
 
        elif typestring == "fakenfs":
 
3490
        if typestring == "fakenfs":
3859
3491
            from bzrlib.tests import test_server
3860
3492
            return test_server.FakeNFSServer
3861
3493
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3874
3506
                                 'throughout the test suite.',
3875
3507
                            type=get_transport_type),
3876
3508
                     Option('benchmark',
3877
 
                            help='Run the benchmarks rather than selftests.',
3878
 
                            hidden=True),
 
3509
                            help='Run the benchmarks rather than selftests.'),
3879
3510
                     Option('lsprof-timed',
3880
3511
                            help='Generate lsprof output for benchmarked'
3881
3512
                                 ' sections of code.'),
3882
3513
                     Option('lsprof-tests',
3883
3514
                            help='Generate lsprof output for each test.'),
 
3515
                     Option('cache-dir', type=str,
 
3516
                            help='Cache intermediate benchmark output in this '
 
3517
                                 'directory.'),
3884
3518
                     Option('first',
3885
3519
                            help='Run all tests, but run specified tests first.',
3886
3520
                            short_name='f',
3895
3529
                     Option('randomize', type=str, argname="SEED",
3896
3530
                            help='Randomize the order of tests using the given'
3897
3531
                                 ' seed or "now" for the current time.'),
3898
 
                     ListOption('exclude', type=str, argname="PATTERN",
3899
 
                                short_name='x',
3900
 
                                help='Exclude tests that match this regular'
3901
 
                                ' expression.'),
 
3532
                     Option('exclude', type=str, argname="PATTERN",
 
3533
                            short_name='x',
 
3534
                            help='Exclude tests that match this regular'
 
3535
                                 ' expression.'),
3902
3536
                     Option('subunit',
3903
3537
                        help='Output test progress via subunit.'),
3904
3538
                     Option('strict', help='Fail on missing dependencies or '
3911
3545
                                param_name='starting_with', short_name='s',
3912
3546
                                help=
3913
3547
                                'Load only the tests starting with TESTID.'),
3914
 
                     Option('sync',
3915
 
                            help="By default we disable fsync and fdatasync"
3916
 
                                 " while running the test suite.")
3917
3548
                     ]
3918
3549
    encoding_type = 'replace'
3919
3550
 
3923
3554
 
3924
3555
    def run(self, testspecs_list=None, verbose=False, one=False,
3925
3556
            transport=None, benchmark=None,
3926
 
            lsprof_timed=None,
 
3557
            lsprof_timed=None, cache_dir=None,
3927
3558
            first=False, list_only=False,
3928
3559
            randomize=None, exclude=None, strict=False,
3929
3560
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3930
 
            parallel=None, lsprof_tests=False,
3931
 
            sync=False):
3932
 
        from bzrlib import tests
3933
 
 
 
3561
            parallel=None, lsprof_tests=False):
 
3562
        from bzrlib.tests import selftest
 
3563
        import bzrlib.benchmarks as benchmarks
 
3564
        from bzrlib.benchmarks import tree_creator
 
3565
 
 
3566
        # Make deprecation warnings visible, unless -Werror is set
 
3567
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3568
 
 
3569
        if cache_dir is not None:
 
3570
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3934
3571
        if testspecs_list is not None:
3935
3572
            pattern = '|'.join(testspecs_list)
3936
3573
        else:
3939
3576
            try:
3940
3577
                from bzrlib.tests import SubUnitBzrRunner
3941
3578
            except ImportError:
3942
 
                raise errors.BzrCommandError(gettext("subunit not available. subunit "
3943
 
                    "needs to be installed to use --subunit."))
 
3579
                raise errors.BzrCommandError("subunit not available. subunit "
 
3580
                    "needs to be installed to use --subunit.")
3944
3581
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3945
3582
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3946
3583
            # stdout, which would corrupt the subunit stream. 
3955
3592
            self.additional_selftest_args.setdefault(
3956
3593
                'suite_decorators', []).append(parallel)
3957
3594
        if benchmark:
3958
 
            raise errors.BzrCommandError(gettext(
3959
 
                "--benchmark is no longer supported from bzr 2.2; "
3960
 
                "use bzr-usertest instead"))
3961
 
        test_suite_factory = None
3962
 
        if not exclude:
3963
 
            exclude_pattern = None
 
3595
            test_suite_factory = benchmarks.test_suite
 
3596
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3597
            verbose = not is_quiet()
 
3598
            # TODO: should possibly lock the history file...
 
3599
            benchfile = open(".perf_history", "at", buffering=1)
 
3600
            self.add_cleanup(benchfile.close)
3964
3601
        else:
3965
 
            exclude_pattern = '(' + '|'.join(exclude) + ')'
3966
 
        if not sync:
3967
 
            self._disable_fsync()
 
3602
            test_suite_factory = None
 
3603
            benchfile = None
3968
3604
        selftest_kwargs = {"verbose": verbose,
3969
3605
                          "pattern": pattern,
3970
3606
                          "stop_on_failure": one,
3972
3608
                          "test_suite_factory": test_suite_factory,
3973
3609
                          "lsprof_timed": lsprof_timed,
3974
3610
                          "lsprof_tests": lsprof_tests,
 
3611
                          "bench_history": benchfile,
3975
3612
                          "matching_tests_first": first,
3976
3613
                          "list_only": list_only,
3977
3614
                          "random_seed": randomize,
3978
 
                          "exclude_pattern": exclude_pattern,
 
3615
                          "exclude_pattern": exclude,
3979
3616
                          "strict": strict,
3980
3617
                          "load_list": load_list,
3981
3618
                          "debug_flags": debugflag,
3982
3619
                          "starting_with": starting_with
3983
3620
                          }
3984
3621
        selftest_kwargs.update(self.additional_selftest_args)
3985
 
 
3986
 
        # Make deprecation warnings visible, unless -Werror is set
3987
 
        cleanup = symbol_versioning.activate_deprecation_warnings(
3988
 
            override=False)
3989
 
        try:
3990
 
            result = tests.selftest(**selftest_kwargs)
3991
 
        finally:
3992
 
            cleanup()
 
3622
        result = selftest(**selftest_kwargs)
3993
3623
        return int(not result)
3994
3624
 
3995
 
    def _disable_fsync(self):
3996
 
        """Change the 'os' functionality to not synchronize."""
3997
 
        self._orig_fsync = getattr(os, 'fsync', None)
3998
 
        if self._orig_fsync is not None:
3999
 
            os.fsync = lambda filedes: None
4000
 
        self._orig_fdatasync = getattr(os, 'fdatasync', None)
4001
 
        if self._orig_fdatasync is not None:
4002
 
            os.fdatasync = lambda filedes: None
4003
 
 
4004
3625
 
4005
3626
class cmd_version(Command):
4006
3627
    __doc__ = """Show version of bzr."""
4026
3647
 
4027
3648
    @display_command
4028
3649
    def run(self):
4029
 
        self.outf.write(gettext("It sure does!\n"))
 
3650
        self.outf.write("It sure does!\n")
4030
3651
 
4031
3652
 
4032
3653
class cmd_find_merge_base(Command):
4050
3671
        graph = branch1.repository.get_graph(branch2.repository)
4051
3672
        base_rev_id = graph.find_unique_lca(last1, last2)
4052
3673
 
4053
 
        self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
 
3674
        self.outf.write('merge base is revision %s\n' % base_rev_id)
4054
3675
 
4055
3676
 
4056
3677
class cmd_merge(Command):
4059
3680
    The source of the merge can be specified either in the form of a branch,
4060
3681
    or in the form of a path to a file containing a merge directive generated
4061
3682
    with bzr send. If neither is specified, the default is the upstream branch
4062
 
    or the branch most recently merged using --remember.  The source of the
4063
 
    merge may also be specified in the form of a path to a file in another
4064
 
    branch:  in this case, only the modifications to that file are merged into
4065
 
    the current working tree.
4066
 
 
4067
 
    When merging from a branch, by default bzr will try to merge in all new
4068
 
    work from the other branch, automatically determining an appropriate base
4069
 
    revision.  If this fails, you may need to give an explicit base.
4070
 
 
4071
 
    To pick a different ending revision, pass "--revision OTHER".  bzr will
4072
 
    try to merge in all new work up to and including revision OTHER.
4073
 
 
4074
 
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
4075
 
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
4076
 
    causes some revisions to be skipped, i.e. if the destination branch does
4077
 
    not already contain revision BASE, such a merge is commonly referred to as
4078
 
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4079
 
    cherrypicks. The changes look like a normal commit, and the history of the
4080
 
    changes from the other branch is not stored in the commit.
4081
 
 
4082
 
    Revision numbers are always relative to the source branch.
 
3683
    or the branch most recently merged using --remember.
 
3684
 
 
3685
    When merging a branch, by default the tip will be merged. To pick a different
 
3686
    revision, pass --revision. If you specify two values, the first will be used as
 
3687
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
3688
    available revisions, like this is commonly referred to as "cherrypicking".
 
3689
 
 
3690
    Revision numbers are always relative to the branch being merged.
 
3691
 
 
3692
    By default, bzr will try to merge in all new work from the other
 
3693
    branch, automatically determining an appropriate base.  If this
 
3694
    fails, you may need to give an explicit base.
4083
3695
 
4084
3696
    Merge will do its best to combine the changes in two branches, but there
4085
3697
    are some kinds of problems only a human can fix.  When it encounters those,
4088
3700
 
4089
3701
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
4090
3702
 
4091
 
    If there is no default branch set, the first merge will set it (use
4092
 
    --no-remember to avoid setting it). After that, you can omit the branch
4093
 
    to use the default.  To change the default, use --remember. The value will
4094
 
    only be saved if the remote location can be accessed.
 
3703
    If there is no default branch set, the first merge will set it. After
 
3704
    that, you can omit the branch to use the default.  To change the
 
3705
    default, use --remember. The value will only be saved if the remote
 
3706
    location can be accessed.
4095
3707
 
4096
3708
    The results of the merge are placed into the destination working
4097
3709
    directory, where they can be reviewed (with bzr diff), tested, and then
4098
3710
    committed to record the result of the merge.
4099
3711
 
4100
3712
    merge refuses to run if there are any uncommitted changes, unless
4101
 
    --force is given.  If --force is given, then the changes from the source 
4102
 
    will be merged with the current working tree, including any uncommitted
4103
 
    changes in the tree.  The --force option can also be used to create a
 
3713
    --force is given. The --force option can also be used to create a
4104
3714
    merge revision which has more than two parents.
4105
3715
 
4106
3716
    If one would like to merge changes from the working tree of the other
4111
3721
    you to apply each diff hunk and file change, similar to "shelve".
4112
3722
 
4113
3723
    :Examples:
4114
 
        To merge all new revisions from bzr.dev::
 
3724
        To merge the latest revision from bzr.dev::
4115
3725
 
4116
3726
            bzr merge ../bzr.dev
4117
3727
 
4164
3774
    ]
4165
3775
 
4166
3776
    def run(self, location=None, revision=None, force=False,
4167
 
            merge_type=None, show_base=False, reprocess=None, remember=None,
 
3777
            merge_type=None, show_base=False, reprocess=None, remember=False,
4168
3778
            uncommitted=False, pull=False,
4169
3779
            directory=None,
4170
3780
            preview=False,
4178
3788
        merger = None
4179
3789
        allow_pending = True
4180
3790
        verified = 'inapplicable'
4181
 
 
4182
3791
        tree = WorkingTree.open_containing(directory)[0]
4183
 
        if tree.branch.revno() == 0:
4184
 
            raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
4185
 
                                         'https://bugs.launchpad.net/bzr/+bug/308562'))
4186
3792
 
4187
3793
        try:
4188
3794
            basis_tree = tree.revision_tree(tree.last_revision())
4208
3814
                mergeable = None
4209
3815
            else:
4210
3816
                if uncommitted:
4211
 
                    raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4212
 
                        ' with bundles or merge directives.'))
 
3817
                    raise errors.BzrCommandError('Cannot use --uncommitted'
 
3818
                        ' with bundles or merge directives.')
4213
3819
 
4214
3820
                if revision is not None:
4215
 
                    raise errors.BzrCommandError(gettext(
4216
 
                        'Cannot use -r with merge directives or bundles'))
 
3821
                    raise errors.BzrCommandError(
 
3822
                        'Cannot use -r with merge directives or bundles')
4217
3823
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
4218
3824
                   mergeable, None)
4219
3825
 
4220
3826
        if merger is None and uncommitted:
4221
3827
            if revision is not None and len(revision) > 0:
4222
 
                raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4223
 
                    ' --revision at the same time.'))
 
3828
                raise errors.BzrCommandError('Cannot use --uncommitted and'
 
3829
                    ' --revision at the same time.')
4224
3830
            merger = self.get_merger_from_uncommitted(tree, location, None)
4225
3831
            allow_pending = False
4226
3832
 
4234
3840
        self.sanity_check_merger(merger)
4235
3841
        if (merger.base_rev_id == merger.other_rev_id and
4236
3842
            merger.other_rev_id is not None):
4237
 
            # check if location is a nonexistent file (and not a branch) to
4238
 
            # disambiguate the 'Nothing to do'
4239
 
            if merger.interesting_files:
4240
 
                if not merger.other_tree.has_filename(
4241
 
                    merger.interesting_files[0]):
4242
 
                    note(gettext("merger: ") + str(merger))
4243
 
                    raise errors.PathsDoNotExist([location])
4244
 
            note(gettext('Nothing to do.'))
 
3843
            note('Nothing to do.')
4245
3844
            return 0
4246
 
        if pull and not preview:
 
3845
        if pull:
4247
3846
            if merger.interesting_files is not None:
4248
 
                raise errors.BzrCommandError(gettext('Cannot pull individual files'))
 
3847
                raise errors.BzrCommandError('Cannot pull individual files')
4249
3848
            if (merger.base_rev_id == tree.last_revision()):
4250
3849
                result = tree.pull(merger.other_branch, False,
4251
3850
                                   merger.other_rev_id)
4252
3851
                result.report(self.outf)
4253
3852
                return 0
4254
3853
        if merger.this_basis is None:
4255
 
            raise errors.BzrCommandError(gettext(
 
3854
            raise errors.BzrCommandError(
4256
3855
                "This branch has no commits."
4257
 
                " (perhaps you would prefer 'bzr pull')"))
 
3856
                " (perhaps you would prefer 'bzr pull')")
4258
3857
        if preview:
4259
3858
            return self._do_preview(merger)
4260
3859
        elif interactive:
4311
3910
    def sanity_check_merger(self, merger):
4312
3911
        if (merger.show_base and
4313
3912
            not merger.merge_type is _mod_merge.Merge3Merger):
4314
 
            raise errors.BzrCommandError(gettext("Show-base is not supported for this"
4315
 
                                         " merge type. %s") % merger.merge_type)
 
3913
            raise errors.BzrCommandError("Show-base is not supported for this"
 
3914
                                         " merge type. %s" % merger.merge_type)
4316
3915
        if merger.reprocess is None:
4317
3916
            if merger.show_base:
4318
3917
                merger.reprocess = False
4320
3919
                # Use reprocess if the merger supports it
4321
3920
                merger.reprocess = merger.merge_type.supports_reprocess
4322
3921
        if merger.reprocess and not merger.merge_type.supports_reprocess:
4323
 
            raise errors.BzrCommandError(gettext("Conflict reduction is not supported"
4324
 
                                         " for merge type %s.") %
 
3922
            raise errors.BzrCommandError("Conflict reduction is not supported"
 
3923
                                         " for merge type %s." %
4325
3924
                                         merger.merge_type)
4326
3925
        if merger.reprocess and merger.show_base:
4327
 
            raise errors.BzrCommandError(gettext("Cannot do conflict reduction and"
4328
 
                                         " show base."))
 
3926
            raise errors.BzrCommandError("Cannot do conflict reduction and"
 
3927
                                         " show base.")
4329
3928
 
4330
3929
    def _get_merger_from_branch(self, tree, location, revision, remember,
4331
3930
                                possible_transports, pb):
4358
3957
        if other_revision_id is None:
4359
3958
            other_revision_id = _mod_revision.ensure_null(
4360
3959
                other_branch.last_revision())
4361
 
        # Remember where we merge from. We need to remember if:
4362
 
        # - user specify a location (and we don't merge from the parent
4363
 
        #   branch)
4364
 
        # - user ask to remember or there is no previous location set to merge
4365
 
        #   from and user didn't ask to *not* remember
4366
 
        if (user_location is not None
4367
 
            and ((remember
4368
 
                  or (remember is None
4369
 
                      and tree.branch.get_submit_branch() is None)))):
 
3960
        # Remember where we merge from
 
3961
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3962
             user_location is not None):
4370
3963
            tree.branch.set_submit_branch(other_branch.base)
4371
 
        # Merge tags (but don't set them in the master branch yet, the user
4372
 
        # might revert this merge).  Commit will propagate them.
4373
 
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
 
3964
        _merge_tags_if_possible(other_branch, tree.branch)
4374
3965
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4375
3966
            other_revision_id, base_revision_id, other_branch, base_branch)
4376
3967
        if other_path != '':
4435
4026
            stored_location_type = "parent"
4436
4027
        mutter("%s", stored_location)
4437
4028
        if stored_location is None:
4438
 
            raise errors.BzrCommandError(gettext("No location specified or remembered"))
 
4029
            raise errors.BzrCommandError("No location specified or remembered")
4439
4030
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
4440
 
        note(gettext("{0} remembered {1} location {2}").format(verb_string,
4441
 
                stored_location_type, display_url))
 
4031
        note(u"%s remembered %s location %s", verb_string,
 
4032
                stored_location_type, display_url)
4442
4033
        return stored_location
4443
4034
 
4444
4035
 
4481
4072
        self.add_cleanup(tree.lock_write().unlock)
4482
4073
        parents = tree.get_parent_ids()
4483
4074
        if len(parents) != 2:
4484
 
            raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
 
4075
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4485
4076
                                         " merges.  Not cherrypicking or"
4486
 
                                         " multi-merges."))
 
4077
                                         " multi-merges.")
4487
4078
        repository = tree.branch.repository
4488
4079
        interesting_ids = None
4489
4080
        new_conflicts = []
4544
4135
    last committed revision is used.
4545
4136
 
4546
4137
    To remove only some changes, without reverting to a prior version, use
4547
 
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
4548
 
    will remove the changes introduced by the second last commit (-2), without
4549
 
    affecting the changes introduced by the last commit (-1).  To remove
4550
 
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
4138
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
4139
    changes introduced by -2, without affecting the changes introduced by -1.
 
4140
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4551
4141
 
4552
4142
    By default, any files that have been manually changed will be backed up
4553
4143
    first.  (Files changed only by merge are not backed up.)  Backup files have
4583
4173
    target branches.
4584
4174
    """
4585
4175
 
4586
 
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4176
    _see_also = ['cat', 'export']
4587
4177
    takes_options = [
4588
4178
        'revision',
4589
4179
        Option('no-backup', "Do not save backups of reverted files."),
4708
4298
            type=_parse_revision_str,
4709
4299
            help='Filter on local branch revisions (inclusive). '
4710
4300
                'See "help revisionspec" for details.'),
4711
 
        Option('include-merged',
 
4301
        Option('include-merges',
4712
4302
               'Show all revisions in addition to the mainline ones.'),
4713
 
        Option('include-merges', hidden=True,
4714
 
               help='Historical alias for --include-merged.'),
4715
4303
        ]
4716
4304
    encoding_type = 'replace'
4717
4305
 
4720
4308
            theirs_only=False,
4721
4309
            log_format=None, long=False, short=False, line=False,
4722
4310
            show_ids=False, verbose=False, this=False, other=False,
4723
 
            include_merged=None, revision=None, my_revision=None,
4724
 
            directory=u'.',
4725
 
            include_merges=symbol_versioning.DEPRECATED_PARAMETER):
 
4311
            include_merges=False, revision=None, my_revision=None,
 
4312
            directory=u'.'):
4726
4313
        from bzrlib.missing import find_unmerged, iter_log_revisions
4727
4314
        def message(s):
4728
4315
            if not is_quiet():
4729
4316
                self.outf.write(s)
4730
4317
 
4731
 
        if symbol_versioning.deprecated_passed(include_merges):
4732
 
            ui.ui_factory.show_user_warning(
4733
 
                'deprecated_command_option',
4734
 
                deprecated_name='--include-merges',
4735
 
                recommended_name='--include-merged',
4736
 
                deprecated_in_version='2.5',
4737
 
                command=self.invoked_as)
4738
 
            if include_merged is None:
4739
 
                include_merged = include_merges
4740
 
            else:
4741
 
                raise errors.BzrCommandError(gettext(
4742
 
                    '{0} and {1} are mutually exclusive').format(
4743
 
                    '--include-merges', '--include-merged'))
4744
 
        if include_merged is None:
4745
 
            include_merged = False
4746
4318
        if this:
4747
4319
            mine_only = this
4748
4320
        if other:
4763
4335
        if other_branch is None:
4764
4336
            other_branch = parent
4765
4337
            if other_branch is None:
4766
 
                raise errors.BzrCommandError(gettext("No peer location known"
4767
 
                                             " or specified."))
 
4338
                raise errors.BzrCommandError("No peer location known"
 
4339
                                             " or specified.")
4768
4340
            display_url = urlutils.unescape_for_display(parent,
4769
4341
                                                        self.outf.encoding)
4770
 
            message(gettext("Using saved parent location: {0}\n").format(
4771
 
                    display_url))
 
4342
            message("Using saved parent location: "
 
4343
                    + display_url + "\n")
4772
4344
 
4773
4345
        remote_branch = Branch.open(other_branch)
4774
4346
        if remote_branch.base == local_branch.base:
4787
4359
        local_extra, remote_extra = find_unmerged(
4788
4360
            local_branch, remote_branch, restrict,
4789
4361
            backward=not reverse,
4790
 
            include_merged=include_merged,
 
4362
            include_merges=include_merges,
4791
4363
            local_revid_range=local_revid_range,
4792
4364
            remote_revid_range=remote_revid_range)
4793
4365
 
4800
4372
 
4801
4373
        status_code = 0
4802
4374
        if local_extra and not theirs_only:
4803
 
            message(ngettext("You have %d extra revision:\n",
4804
 
                             "You have %d extra revisions:\n", 
4805
 
                             len(local_extra)) %
 
4375
            message("You have %d extra revision(s):\n" %
4806
4376
                len(local_extra))
4807
4377
            for revision in iter_log_revisions(local_extra,
4808
4378
                                local_branch.repository,
4816
4386
        if remote_extra and not mine_only:
4817
4387
            if printed_local is True:
4818
4388
                message("\n\n\n")
4819
 
            message(ngettext("You are missing %d revision:\n",
4820
 
                             "You are missing %d revisions:\n",
4821
 
                             len(remote_extra)) %
 
4389
            message("You are missing %d revision(s):\n" %
4822
4390
                len(remote_extra))
4823
4391
            for revision in iter_log_revisions(remote_extra,
4824
4392
                                remote_branch.repository,
4828
4396
 
4829
4397
        if mine_only and not local_extra:
4830
4398
            # We checked local, and found nothing extra
4831
 
            message(gettext('This branch has no new revisions.\n'))
 
4399
            message('This branch is up to date.\n')
4832
4400
        elif theirs_only and not remote_extra:
4833
4401
            # We checked remote, and found nothing extra
4834
 
            message(gettext('Other branch has no new revisions.\n'))
 
4402
            message('Other branch is up to date.\n')
4835
4403
        elif not (mine_only or theirs_only or local_extra or
4836
4404
                  remote_extra):
4837
4405
            # We checked both branches, and neither one had extra
4838
4406
            # revisions
4839
 
            message(gettext("Branches are up to date.\n"))
 
4407
            message("Branches are up to date.\n")
4840
4408
        self.cleanup_now()
4841
4409
        if not status_code and parent is None and other_branch is not None:
4842
4410
            self.add_cleanup(local_branch.lock_write().unlock)
4872
4440
        ]
4873
4441
 
4874
4442
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4875
 
        dir = controldir.ControlDir.open_containing(branch_or_repo)[0]
 
4443
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4876
4444
        try:
4877
4445
            branch = dir.open_branch()
4878
4446
            repository = branch.repository
4904
4472
 
4905
4473
    @display_command
4906
4474
    def run(self, verbose=False):
4907
 
        from bzrlib import plugin
4908
 
        # Don't give writelines a generator as some codecs don't like that
4909
 
        self.outf.writelines(
4910
 
            list(plugin.describe_plugins(show_paths=verbose)))
 
4475
        import bzrlib.plugin
 
4476
        from inspect import getdoc
 
4477
        result = []
 
4478
        for name, plugin in bzrlib.plugin.plugins().items():
 
4479
            version = plugin.__version__
 
4480
            if version == 'unknown':
 
4481
                version = ''
 
4482
            name_ver = '%s %s' % (name, version)
 
4483
            d = getdoc(plugin.module)
 
4484
            if d:
 
4485
                doc = d.split('\n')[0]
 
4486
            else:
 
4487
                doc = '(no description)'
 
4488
            result.append((name_ver, doc, plugin.path()))
 
4489
        for name_ver, doc, path in sorted(result):
 
4490
            self.outf.write("%s\n" % name_ver)
 
4491
            self.outf.write("   %s\n" % doc)
 
4492
            if verbose:
 
4493
                self.outf.write("   %s\n" % path)
 
4494
            self.outf.write("\n")
4911
4495
 
4912
4496
 
4913
4497
class cmd_testament(Command):
4966
4550
    @display_command
4967
4551
    def run(self, filename, all=False, long=False, revision=None,
4968
4552
            show_ids=False, directory=None):
4969
 
        from bzrlib.annotate import (
4970
 
            annotate_file_tree,
4971
 
            )
 
4553
        from bzrlib.annotate import annotate_file, annotate_file_tree
4972
4554
        wt, branch, relpath = \
4973
4555
            _open_directory_or_containing_tree_or_branch(filename, directory)
4974
4556
        if wt is not None:
4977
4559
            self.add_cleanup(branch.lock_read().unlock)
4978
4560
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4979
4561
        self.add_cleanup(tree.lock_read().unlock)
4980
 
        if wt is not None and revision is None:
 
4562
        if wt is not None:
4981
4563
            file_id = wt.path2id(relpath)
4982
4564
        else:
4983
4565
            file_id = tree.path2id(relpath)
4984
4566
        if file_id is None:
4985
4567
            raise errors.NotVersionedError(filename)
 
4568
        file_version = tree.inventory[file_id].revision
4986
4569
        if wt is not None and revision is None:
4987
4570
            # If there is a tree and we're not annotating historical
4988
4571
            # versions, annotate the working tree's content.
4989
4572
            annotate_file_tree(wt, file_id, self.outf, long, all,
4990
4573
                show_ids=show_ids)
4991
4574
        else:
4992
 
            annotate_file_tree(tree, file_id, self.outf, long, all,
4993
 
                show_ids=show_ids, branch=branch)
 
4575
            annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4576
                          show_ids=show_ids)
4994
4577
 
4995
4578
 
4996
4579
class cmd_re_sign(Command):
5003
4586
 
5004
4587
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
5005
4588
        if revision_id_list is not None and revision is not None:
5006
 
            raise errors.BzrCommandError(gettext('You can only supply one of revision_id or --revision'))
 
4589
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
5007
4590
        if revision_id_list is None and revision is None:
5008
 
            raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
 
4591
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
5009
4592
        b = WorkingTree.open_containing(directory)[0].branch
5010
4593
        self.add_cleanup(b.lock_write().unlock)
5011
4594
        return self._run(b, revision_id_list, revision)
5043
4626
                if to_revid is None:
5044
4627
                    to_revno = b.revno()
5045
4628
                if from_revno is None or to_revno is None:
5046
 
                    raise errors.BzrCommandError(gettext('Cannot sign a range of non-revision-history revisions'))
 
4629
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
5047
4630
                b.repository.start_write_group()
5048
4631
                try:
5049
4632
                    for revno in range(from_revno, to_revno + 1):
5055
4638
                else:
5056
4639
                    b.repository.commit_write_group()
5057
4640
            else:
5058
 
                raise errors.BzrCommandError(gettext('Please supply either one revision, or a range.'))
 
4641
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
5059
4642
 
5060
4643
 
5061
4644
class cmd_bind(Command):
5080
4663
            try:
5081
4664
                location = b.get_old_bound_location()
5082
4665
            except errors.UpgradeRequired:
5083
 
                raise errors.BzrCommandError(gettext('No location supplied.  '
5084
 
                    'This format does not remember old locations.'))
 
4666
                raise errors.BzrCommandError('No location supplied.  '
 
4667
                    'This format does not remember old locations.')
5085
4668
            else:
5086
4669
                if location is None:
5087
4670
                    if b.get_bound_location() is not None:
5088
 
                        raise errors.BzrCommandError(gettext('Branch is already bound'))
 
4671
                        raise errors.BzrCommandError('Branch is already bound')
5089
4672
                    else:
5090
 
                        raise errors.BzrCommandError(gettext('No location supplied '
5091
 
                            'and no previous location known'))
 
4673
                        raise errors.BzrCommandError('No location supplied '
 
4674
                            'and no previous location known')
5092
4675
        b_other = Branch.open(location)
5093
4676
        try:
5094
4677
            b.bind(b_other)
5095
4678
        except errors.DivergedBranches:
5096
 
            raise errors.BzrCommandError(gettext('These branches have diverged.'
5097
 
                                         ' Try merging, and then bind again.'))
 
4679
            raise errors.BzrCommandError('These branches have diverged.'
 
4680
                                         ' Try merging, and then bind again.')
5098
4681
        if b.get_config().has_explicit_nickname():
5099
4682
            b.nick = b_other.nick
5100
4683
 
5113
4696
    def run(self, directory=u'.'):
5114
4697
        b, relpath = Branch.open_containing(directory)
5115
4698
        if not b.unbind():
5116
 
            raise errors.BzrCommandError(gettext('Local branch is not bound'))
 
4699
            raise errors.BzrCommandError('Local branch is not bound')
5117
4700
 
5118
4701
 
5119
4702
class cmd_uncommit(Command):
5140
4723
    takes_options = ['verbose', 'revision',
5141
4724
                    Option('dry-run', help='Don\'t actually make changes.'),
5142
4725
                    Option('force', help='Say yes to all questions.'),
5143
 
                    Option('keep-tags',
5144
 
                           help='Keep tags that point to removed revisions.'),
5145
4726
                    Option('local',
5146
4727
                           help="Only remove the commits from the local branch"
5147
4728
                                " when in a checkout."
5151
4732
    aliases = []
5152
4733
    encoding_type = 'replace'
5153
4734
 
5154
 
    def run(self, location=None, dry_run=False, verbose=False,
5155
 
            revision=None, force=False, local=False, keep_tags=False):
 
4735
    def run(self, location=None,
 
4736
            dry_run=False, verbose=False,
 
4737
            revision=None, force=False, local=False):
5156
4738
        if location is None:
5157
4739
            location = u'.'
5158
 
        control, relpath = controldir.ControlDir.open_containing(location)
 
4740
        control, relpath = bzrdir.BzrDir.open_containing(location)
5159
4741
        try:
5160
4742
            tree = control.open_workingtree()
5161
4743
            b = tree.branch
5167
4749
            self.add_cleanup(tree.lock_write().unlock)
5168
4750
        else:
5169
4751
            self.add_cleanup(b.lock_write().unlock)
5170
 
        return self._run(b, tree, dry_run, verbose, revision, force,
5171
 
                         local, keep_tags)
 
4752
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
5172
4753
 
5173
 
    def _run(self, b, tree, dry_run, verbose, revision, force, local,
5174
 
             keep_tags):
 
4754
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
5175
4755
        from bzrlib.log import log_formatter, show_log
5176
4756
        from bzrlib.uncommit import uncommit
5177
4757
 
5192
4772
                rev_id = b.get_rev_id(revno)
5193
4773
 
5194
4774
        if rev_id is None or _mod_revision.is_null(rev_id):
5195
 
            self.outf.write(gettext('No revisions to uncommit.\n'))
 
4775
            self.outf.write('No revisions to uncommit.\n')
5196
4776
            return 1
5197
4777
 
5198
4778
        lf = log_formatter('short',
5207
4787
                 end_revision=last_revno)
5208
4788
 
5209
4789
        if dry_run:
5210
 
            self.outf.write(gettext('Dry-run, pretending to remove'
5211
 
                            ' the above revisions.\n'))
 
4790
            self.outf.write('Dry-run, pretending to remove'
 
4791
                            ' the above revisions.\n')
5212
4792
        else:
5213
 
            self.outf.write(gettext('The above revision(s) will be removed.\n'))
 
4793
            self.outf.write('The above revision(s) will be removed.\n')
5214
4794
 
5215
4795
        if not force:
5216
 
            if not ui.ui_factory.confirm_action(
5217
 
                    gettext(u'Uncommit these revisions'),
5218
 
                    'bzrlib.builtins.uncommit',
5219
 
                    {}):
5220
 
                self.outf.write(gettext('Canceled\n'))
 
4796
            if not ui.ui_factory.get_boolean('Are you sure'):
 
4797
                self.outf.write('Canceled')
5221
4798
                return 0
5222
4799
 
5223
4800
        mutter('Uncommitting from {%s} to {%s}',
5224
4801
               last_rev_id, rev_id)
5225
4802
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
5226
 
                 revno=revno, local=local, keep_tags=keep_tags)
5227
 
        self.outf.write(gettext('You can restore the old tip by running:\n'
5228
 
             '  bzr pull . -r revid:%s\n') % last_rev_id)
 
4803
                 revno=revno, local=local)
 
4804
        self.outf.write('You can restore the old tip by running:\n'
 
4805
             '  bzr pull . -r revid:%s\n' % last_rev_id)
5229
4806
 
5230
4807
 
5231
4808
class cmd_break_lock(Command):
5232
 
    __doc__ = """Break a dead lock.
5233
 
 
5234
 
    This command breaks a lock on a repository, branch, working directory or
5235
 
    config file.
 
4809
    __doc__ = """Break a dead lock on a repository, branch or working directory.
5236
4810
 
5237
4811
    CAUTION: Locks should only be broken when you are sure that the process
5238
4812
    holding the lock has been stopped.
5243
4817
    :Examples:
5244
4818
        bzr break-lock
5245
4819
        bzr break-lock bzr+ssh://example.com/bzr/foo
5246
 
        bzr break-lock --conf ~/.bazaar
5247
4820
    """
5248
 
 
5249
4821
    takes_args = ['location?']
5250
 
    takes_options = [
5251
 
        Option('config',
5252
 
               help='LOCATION is the directory where the config lock is.'),
5253
 
        Option('force',
5254
 
            help='Do not ask for confirmation before breaking the lock.'),
5255
 
        ]
5256
4822
 
5257
 
    def run(self, location=None, config=False, force=False):
 
4823
    def run(self, location=None, show=False):
5258
4824
        if location is None:
5259
4825
            location = u'.'
5260
 
        if force:
5261
 
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5262
 
                None,
5263
 
                {'bzrlib.lockdir.break': True})
5264
 
        if config:
5265
 
            conf = _mod_config.LockableConfig(file_name=location)
5266
 
            conf.break_lock()
5267
 
        else:
5268
 
            control, relpath = controldir.ControlDir.open_containing(location)
5269
 
            try:
5270
 
                control.break_lock()
5271
 
            except NotImplementedError:
5272
 
                pass
 
4826
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4827
        try:
 
4828
            control.break_lock()
 
4829
        except NotImplementedError:
 
4830
            pass
5273
4831
 
5274
4832
 
5275
4833
class cmd_wait_until_signalled(Command):
5315
4873
                    'option leads to global uncontrolled write access to your '
5316
4874
                    'file system.'
5317
4875
                ),
5318
 
        Option('client-timeout', type=float,
5319
 
               help='Override the default idle client timeout (5min).'),
5320
4876
        ]
5321
4877
 
5322
4878
    def get_host_and_port(self, port):
5339
4895
        return host, port
5340
4896
 
5341
4897
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
5342
 
            protocol=None, client_timeout=None):
 
4898
            protocol=None):
5343
4899
        from bzrlib import transport
5344
4900
        if directory is None:
5345
4901
            directory = os.getcwd()
5350
4906
        if not allow_writes:
5351
4907
            url = 'readonly+' + url
5352
4908
        t = transport.get_transport(url)
5353
 
        try:
5354
 
            protocol(t, host, port, inet, client_timeout)
5355
 
        except TypeError, e:
5356
 
            # We use symbol_versioning.deprecated_in just so that people
5357
 
            # grepping can find it here.
5358
 
            # symbol_versioning.deprecated_in((2, 5, 0))
5359
 
            symbol_versioning.warn(
5360
 
                'Got TypeError(%s)\ntrying to call protocol: %s.%s\n'
5361
 
                'Most likely it needs to be updated to support a'
5362
 
                ' "timeout" parameter (added in bzr 2.5.0)'
5363
 
                % (e, protocol.__module__, protocol),
5364
 
                DeprecationWarning)
5365
 
            protocol(t, host, port, inet)
 
4909
        protocol(t, host, port, inet)
5366
4910
 
5367
4911
 
5368
4912
class cmd_join(Command):
5374
4918
    not part of it.  (Such trees can be produced by "bzr split", but also by
5375
4919
    running "bzr branch" with the target inside a tree.)
5376
4920
 
5377
 
    The result is a combined tree, with the subtree no longer an independent
 
4921
    The result is a combined tree, with the subtree no longer an independant
5378
4922
    part.  This is marked as a merge of the subtree into the containing tree,
5379
4923
    and all history is preserved.
5380
4924
    """
5391
4935
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
5392
4936
        repo = containing_tree.branch.repository
5393
4937
        if not repo.supports_rich_root():
5394
 
            raise errors.BzrCommandError(gettext(
 
4938
            raise errors.BzrCommandError(
5395
4939
                "Can't join trees because %s doesn't support rich root data.\n"
5396
 
                "You can use bzr upgrade on the repository.")
 
4940
                "You can use bzr upgrade on the repository."
5397
4941
                % (repo,))
5398
4942
        if reference:
5399
4943
            try:
5401
4945
            except errors.BadReferenceTarget, e:
5402
4946
                # XXX: Would be better to just raise a nicely printable
5403
4947
                # exception from the real origin.  Also below.  mbp 20070306
5404
 
                raise errors.BzrCommandError(
5405
 
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
4948
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
4949
                                             (tree, e.reason))
5406
4950
        else:
5407
4951
            try:
5408
4952
                containing_tree.subsume(sub_tree)
5409
4953
            except errors.BadSubsumeSource, e:
5410
 
                raise errors.BzrCommandError(
5411
 
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
4954
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
4955
                                             (tree, e.reason))
5412
4956
 
5413
4957
 
5414
4958
class cmd_split(Command):
5498
5042
        if submit_branch is None:
5499
5043
            submit_branch = branch.get_parent()
5500
5044
        if submit_branch is None:
5501
 
            raise errors.BzrCommandError(gettext('No submit branch specified or known'))
 
5045
            raise errors.BzrCommandError('No submit branch specified or known')
5502
5046
 
5503
5047
        stored_public_branch = branch.get_public_branch()
5504
5048
        if public_branch is None:
5506
5050
        elif stored_public_branch is None:
5507
5051
            branch.set_public_branch(public_branch)
5508
5052
        if not include_bundle and public_branch is None:
5509
 
            raise errors.BzrCommandError(gettext('No public branch specified or'
5510
 
                                         ' known'))
 
5053
            raise errors.BzrCommandError('No public branch specified or'
 
5054
                                         ' known')
5511
5055
        base_revision_id = None
5512
5056
        if revision is not None:
5513
5057
            if len(revision) > 2:
5514
 
                raise errors.BzrCommandError(gettext('bzr merge-directive takes '
5515
 
                    'at most two one revision identifiers'))
 
5058
                raise errors.BzrCommandError('bzr merge-directive takes '
 
5059
                    'at most two one revision identifiers')
5516
5060
            revision_id = revision[-1].as_revision_id(branch)
5517
5061
            if len(revision) == 2:
5518
5062
                base_revision_id = revision[0].as_revision_id(branch)
5520
5064
            revision_id = branch.last_revision()
5521
5065
        revision_id = ensure_null(revision_id)
5522
5066
        if revision_id == NULL_REVISION:
5523
 
            raise errors.BzrCommandError(gettext('No revisions to bundle.'))
 
5067
            raise errors.BzrCommandError('No revisions to bundle.')
5524
5068
        directive = merge_directive.MergeDirective2.from_objects(
5525
5069
            branch.repository, revision_id, time.time(),
5526
5070
            osutils.local_time_offset(), submit_branch,
5570
5114
    source branch defaults to that containing the working directory, but can
5571
5115
    be changed using --from.
5572
5116
 
5573
 
    Both the submit branch and the public branch follow the usual behavior with
5574
 
    respect to --remember: If there is no default location set, the first send
5575
 
    will set it (use --no-remember to avoid setting it). After that, you can
5576
 
    omit the location to use the default.  To change the default, use
5577
 
    --remember. The value will only be saved if the location can be accessed.
5578
 
 
5579
5117
    In order to calculate those changes, bzr must analyse the submit branch.
5580
5118
    Therefore it is most efficient for the submit branch to be a local mirror.
5581
5119
    If a public location is known for the submit_branch, that location is used
5650
5188
        ]
5651
5189
 
5652
5190
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5653
 
            no_patch=False, revision=None, remember=None, output=None,
 
5191
            no_patch=False, revision=None, remember=False, output=None,
5654
5192
            format=None, mail_to=None, message=None, body=None,
5655
5193
            strict=None, **kwargs):
5656
5194
        from bzrlib.send import send
5780
5318
        self.add_cleanup(branch.lock_write().unlock)
5781
5319
        if delete:
5782
5320
            if tag_name is None:
5783
 
                raise errors.BzrCommandError(gettext("No tag specified to delete."))
 
5321
                raise errors.BzrCommandError("No tag specified to delete.")
5784
5322
            branch.tags.delete_tag(tag_name)
5785
 
            note(gettext('Deleted tag %s.') % tag_name)
 
5323
            self.outf.write('Deleted tag %s.\n' % tag_name)
5786
5324
        else:
5787
5325
            if revision:
5788
5326
                if len(revision) != 1:
5789
 
                    raise errors.BzrCommandError(gettext(
 
5327
                    raise errors.BzrCommandError(
5790
5328
                        "Tags can only be placed on a single revision, "
5791
 
                        "not on a range"))
 
5329
                        "not on a range")
5792
5330
                revision_id = revision[0].as_revision_id(branch)
5793
5331
            else:
5794
5332
                revision_id = branch.last_revision()
5795
5333
            if tag_name is None:
5796
5334
                tag_name = branch.automatic_tag_name(revision_id)
5797
5335
                if tag_name is None:
5798
 
                    raise errors.BzrCommandError(gettext(
5799
 
                        "Please specify a tag name."))
5800
 
            try:
5801
 
                existing_target = branch.tags.lookup_tag(tag_name)
5802
 
            except errors.NoSuchTag:
5803
 
                existing_target = None
5804
 
            if not force and existing_target not in (None, revision_id):
 
5336
                    raise errors.BzrCommandError(
 
5337
                        "Please specify a tag name.")
 
5338
            if (not force) and branch.tags.has_tag(tag_name):
5805
5339
                raise errors.TagAlreadyExists(tag_name)
5806
 
            if existing_target == revision_id:
5807
 
                note(gettext('Tag %s already exists for that revision.') % tag_name)
5808
 
            else:
5809
 
                branch.tags.set_tag(tag_name, revision_id)
5810
 
                if existing_target is None:
5811
 
                    note(gettext('Created tag %s.') % tag_name)
5812
 
                else:
5813
 
                    note(gettext('Updated tag %s.') % tag_name)
 
5340
            branch.tags.set_tag(tag_name, revision_id)
 
5341
            self.outf.write('Created tag %s.\n' % tag_name)
5814
5342
 
5815
5343
 
5816
5344
class cmd_tags(Command):
5823
5351
    takes_options = [
5824
5352
        custom_help('directory',
5825
5353
            help='Branch whose tags should be displayed.'),
5826
 
        RegistryOption('sort',
 
5354
        RegistryOption.from_kwargs('sort',
5827
5355
            'Sort tags by different criteria.', title='Sorting',
5828
 
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
 
5356
            alpha='Sort tags lexicographically (default).',
 
5357
            time='Sort tags chronologically.',
5829
5358
            ),
5830
5359
        'show-ids',
5831
5360
        'revision',
5832
5361
    ]
5833
5362
 
5834
5363
    @display_command
5835
 
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
5836
 
        from bzrlib.tag import tag_sort_methods
 
5364
    def run(self,
 
5365
            directory='.',
 
5366
            sort='alpha',
 
5367
            show_ids=False,
 
5368
            revision=None,
 
5369
            ):
5837
5370
        branch, relpath = Branch.open_containing(directory)
5838
5371
 
5839
5372
        tags = branch.tags.get_tag_dict().items()
5842
5375
 
5843
5376
        self.add_cleanup(branch.lock_read().unlock)
5844
5377
        if revision:
5845
 
            # Restrict to the specified range
5846
 
            tags = self._tags_for_range(branch, revision)
5847
 
        if sort is None:
5848
 
            sort = tag_sort_methods.get()
5849
 
        sort(branch, tags)
 
5378
            graph = branch.repository.get_graph()
 
5379
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5380
            revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5381
            # only show revisions between revid1 and revid2 (inclusive)
 
5382
            tags = [(tag, revid) for tag, revid in tags if
 
5383
                graph.is_between(revid, revid1, revid2)]
 
5384
        if sort == 'alpha':
 
5385
            tags.sort()
 
5386
        elif sort == 'time':
 
5387
            timestamps = {}
 
5388
            for tag, revid in tags:
 
5389
                try:
 
5390
                    revobj = branch.repository.get_revision(revid)
 
5391
                except errors.NoSuchRevision:
 
5392
                    timestamp = sys.maxint # place them at the end
 
5393
                else:
 
5394
                    timestamp = revobj.timestamp
 
5395
                timestamps[revid] = timestamp
 
5396
            tags.sort(key=lambda x: timestamps[x[1]])
5850
5397
        if not show_ids:
5851
5398
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5852
5399
            for index, (tag, revid) in enumerate(tags):
5854
5401
                    revno = branch.revision_id_to_dotted_revno(revid)
5855
5402
                    if isinstance(revno, tuple):
5856
5403
                        revno = '.'.join(map(str, revno))
5857
 
                except (errors.NoSuchRevision,
5858
 
                        errors.GhostRevisionsHaveNoRevno,
5859
 
                        errors.UnsupportedOperation):
 
5404
                except errors.NoSuchRevision:
5860
5405
                    # Bad tag data/merges can lead to tagged revisions
5861
5406
                    # which are not in this branch. Fail gracefully ...
5862
5407
                    revno = '?'
5865
5410
        for tag, revspec in tags:
5866
5411
            self.outf.write('%-20s %s\n' % (tag, revspec))
5867
5412
 
5868
 
    def _tags_for_range(self, branch, revision):
5869
 
        range_valid = True
5870
 
        rev1, rev2 = _get_revision_range(revision, branch, self.name())
5871
 
        revid1, revid2 = rev1.rev_id, rev2.rev_id
5872
 
        # _get_revision_range will always set revid2 if it's not specified.
5873
 
        # If revid1 is None, it means we want to start from the branch
5874
 
        # origin which is always a valid ancestor. If revid1 == revid2, the
5875
 
        # ancestry check is useless.
5876
 
        if revid1 and revid1 != revid2:
5877
 
            # FIXME: We really want to use the same graph than
5878
 
            # branch.iter_merge_sorted_revisions below, but this is not
5879
 
            # easily available -- vila 2011-09-23
5880
 
            if branch.repository.get_graph().is_ancestor(revid2, revid1):
5881
 
                # We don't want to output anything in this case...
5882
 
                return []
5883
 
        # only show revisions between revid1 and revid2 (inclusive)
5884
 
        tagged_revids = branch.tags.get_reverse_tag_dict()
5885
 
        found = []
5886
 
        for r in branch.iter_merge_sorted_revisions(
5887
 
            start_revision_id=revid2, stop_revision_id=revid1,
5888
 
            stop_rule='include'):
5889
 
            revid_tags = tagged_revids.get(r[0], None)
5890
 
            if revid_tags:
5891
 
                found.extend([(tag, r[0]) for tag in revid_tags])
5892
 
        return found
5893
 
 
5894
5413
 
5895
5414
class cmd_reconfigure(Command):
5896
5415
    __doc__ = """Reconfigure the type of a bzr directory.
5910
5429
    takes_args = ['location?']
5911
5430
    takes_options = [
5912
5431
        RegistryOption.from_kwargs(
5913
 
            'tree_type',
5914
 
            title='Tree type',
5915
 
            help='The relation between branch and tree.',
 
5432
            'target_type',
 
5433
            title='Target type',
 
5434
            help='The type to reconfigure the directory to.',
5916
5435
            value_switches=True, enum_switch=False,
5917
5436
            branch='Reconfigure to be an unbound branch with no working tree.',
5918
5437
            tree='Reconfigure to be an unbound branch with a working tree.',
5919
5438
            checkout='Reconfigure to be a bound branch with a working tree.',
5920
5439
            lightweight_checkout='Reconfigure to be a lightweight'
5921
5440
                ' checkout (with no local history).',
5922
 
            ),
5923
 
        RegistryOption.from_kwargs(
5924
 
            'repository_type',
5925
 
            title='Repository type',
5926
 
            help='Location fo the repository.',
5927
 
            value_switches=True, enum_switch=False,
5928
5441
            standalone='Reconfigure to be a standalone branch '
5929
5442
                '(i.e. stop using shared repository).',
5930
5443
            use_shared='Reconfigure to use a shared repository.',
5931
 
            ),
5932
 
        RegistryOption.from_kwargs(
5933
 
            'repository_trees',
5934
 
            title='Trees in Repository',
5935
 
            help='Whether new branches in the repository have trees.',
5936
 
            value_switches=True, enum_switch=False,
5937
5444
            with_trees='Reconfigure repository to create '
5938
5445
                'working trees on branches by default.',
5939
5446
            with_no_trees='Reconfigure repository to not create '
5953
5460
            ),
5954
5461
        ]
5955
5462
 
5956
 
    def run(self, location=None, bind_to=None, force=False,
5957
 
            tree_type=None, repository_type=None, repository_trees=None,
5958
 
            stacked_on=None, unstacked=None):
5959
 
        directory = controldir.ControlDir.open(location)
 
5463
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5464
            stacked_on=None,
 
5465
            unstacked=None):
 
5466
        directory = bzrdir.BzrDir.open(location)
5960
5467
        if stacked_on and unstacked:
5961
 
            raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
 
5468
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5962
5469
        elif stacked_on is not None:
5963
5470
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5964
5471
        elif unstacked:
5966
5473
        # At the moment you can use --stacked-on and a different
5967
5474
        # reconfiguration shape at the same time; there seems no good reason
5968
5475
        # to ban it.
5969
 
        if (tree_type is None and
5970
 
            repository_type is None and
5971
 
            repository_trees is None):
 
5476
        if target_type is None:
5972
5477
            if stacked_on or unstacked:
5973
5478
                return
5974
5479
            else:
5975
 
                raise errors.BzrCommandError(gettext('No target configuration '
5976
 
                    'specified'))
5977
 
        reconfiguration = None
5978
 
        if tree_type == 'branch':
 
5480
                raise errors.BzrCommandError('No target configuration '
 
5481
                    'specified')
 
5482
        elif target_type == 'branch':
5979
5483
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5980
 
        elif tree_type == 'tree':
 
5484
        elif target_type == 'tree':
5981
5485
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5982
 
        elif tree_type == 'checkout':
 
5486
        elif target_type == 'checkout':
5983
5487
            reconfiguration = reconfigure.Reconfigure.to_checkout(
5984
5488
                directory, bind_to)
5985
 
        elif tree_type == 'lightweight-checkout':
 
5489
        elif target_type == 'lightweight-checkout':
5986
5490
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5987
5491
                directory, bind_to)
5988
 
        if reconfiguration:
5989
 
            reconfiguration.apply(force)
5990
 
            reconfiguration = None
5991
 
        if repository_type == 'use-shared':
 
5492
        elif target_type == 'use-shared':
5992
5493
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5993
 
        elif repository_type == 'standalone':
 
5494
        elif target_type == 'standalone':
5994
5495
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5995
 
        if reconfiguration:
5996
 
            reconfiguration.apply(force)
5997
 
            reconfiguration = None
5998
 
        if repository_trees == 'with-trees':
 
5496
        elif target_type == 'with-trees':
5999
5497
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6000
5498
                directory, True)
6001
 
        elif repository_trees == 'with-no-trees':
 
5499
        elif target_type == 'with-no-trees':
6002
5500
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6003
5501
                directory, False)
6004
 
        if reconfiguration:
6005
 
            reconfiguration.apply(force)
6006
 
            reconfiguration = None
 
5502
        reconfiguration.apply(force)
6007
5503
 
6008
5504
 
6009
5505
class cmd_switch(Command):
6044
5540
        from bzrlib import switch
6045
5541
        tree_location = directory
6046
5542
        revision = _get_one_revision('switch', revision)
6047
 
        control_dir = controldir.ControlDir.open_containing(tree_location)[0]
 
5543
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
6048
5544
        if to_location is None:
6049
5545
            if revision is None:
6050
 
                raise errors.BzrCommandError(gettext('You must supply either a'
6051
 
                                             ' revision or a location'))
 
5546
                raise errors.BzrCommandError('You must supply either a'
 
5547
                                             ' revision or a location')
6052
5548
            to_location = tree_location
6053
5549
        try:
6054
5550
            branch = control_dir.open_branch()
6058
5554
            had_explicit_nick = False
6059
5555
        if create_branch:
6060
5556
            if branch is None:
6061
 
                raise errors.BzrCommandError(gettext('cannot create branch without'
6062
 
                                             ' source branch'))
 
5557
                raise errors.BzrCommandError('cannot create branch without'
 
5558
                                             ' source branch')
6063
5559
            to_location = directory_service.directories.dereference(
6064
5560
                              to_location)
6065
5561
            if '/' not in to_location and '\\' not in to_location:
6082
5578
        if had_explicit_nick:
6083
5579
            branch = control_dir.open_branch() #get the new branch!
6084
5580
            branch.nick = to_branch.nick
6085
 
        note(gettext('Switched to branch: %s'),
 
5581
        note('Switched to branch: %s',
6086
5582
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
6087
5583
 
6088
5584
    def _get_branch_location(self, control_dir):
6197
5693
            name = current_view
6198
5694
        if delete:
6199
5695
            if file_list:
6200
 
                raise errors.BzrCommandError(gettext(
6201
 
                    "Both --delete and a file list specified"))
 
5696
                raise errors.BzrCommandError(
 
5697
                    "Both --delete and a file list specified")
6202
5698
            elif switch:
6203
 
                raise errors.BzrCommandError(gettext(
6204
 
                    "Both --delete and --switch specified"))
 
5699
                raise errors.BzrCommandError(
 
5700
                    "Both --delete and --switch specified")
6205
5701
            elif all:
6206
5702
                tree.views.set_view_info(None, {})
6207
 
                self.outf.write(gettext("Deleted all views.\n"))
 
5703
                self.outf.write("Deleted all views.\n")
6208
5704
            elif name is None:
6209
 
                raise errors.BzrCommandError(gettext("No current view to delete"))
 
5705
                raise errors.BzrCommandError("No current view to delete")
6210
5706
            else:
6211
5707
                tree.views.delete_view(name)
6212
 
                self.outf.write(gettext("Deleted '%s' view.\n") % name)
 
5708
                self.outf.write("Deleted '%s' view.\n" % name)
6213
5709
        elif switch:
6214
5710
            if file_list:
6215
 
                raise errors.BzrCommandError(gettext(
6216
 
                    "Both --switch and a file list specified"))
 
5711
                raise errors.BzrCommandError(
 
5712
                    "Both --switch and a file list specified")
6217
5713
            elif all:
6218
 
                raise errors.BzrCommandError(gettext(
6219
 
                    "Both --switch and --all specified"))
 
5714
                raise errors.BzrCommandError(
 
5715
                    "Both --switch and --all specified")
6220
5716
            elif switch == 'off':
6221
5717
                if current_view is None:
6222
 
                    raise errors.BzrCommandError(gettext("No current view to disable"))
 
5718
                    raise errors.BzrCommandError("No current view to disable")
6223
5719
                tree.views.set_view_info(None, view_dict)
6224
 
                self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
 
5720
                self.outf.write("Disabled '%s' view.\n" % (current_view))
6225
5721
            else:
6226
5722
                tree.views.set_view_info(switch, view_dict)
6227
5723
                view_str = views.view_display_str(tree.views.lookup_view())
6228
 
                self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
 
5724
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
6229
5725
        elif all:
6230
5726
            if view_dict:
6231
 
                self.outf.write(gettext('Views defined:\n'))
 
5727
                self.outf.write('Views defined:\n')
6232
5728
                for view in sorted(view_dict):
6233
5729
                    if view == current_view:
6234
5730
                        active = "=>"
6237
5733
                    view_str = views.view_display_str(view_dict[view])
6238
5734
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
6239
5735
            else:
6240
 
                self.outf.write(gettext('No views defined.\n'))
 
5736
                self.outf.write('No views defined.\n')
6241
5737
        elif file_list:
6242
5738
            if name is None:
6243
5739
                # No name given and no current view set
6244
5740
                name = 'my'
6245
5741
            elif name == 'off':
6246
 
                raise errors.BzrCommandError(gettext(
6247
 
                    "Cannot change the 'off' pseudo view"))
 
5742
                raise errors.BzrCommandError(
 
5743
                    "Cannot change the 'off' pseudo view")
6248
5744
            tree.views.set_view(name, sorted(file_list))
6249
5745
            view_str = views.view_display_str(tree.views.lookup_view())
6250
 
            self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
 
5746
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
6251
5747
        else:
6252
5748
            # list the files
6253
5749
            if name is None:
6254
5750
                # No name given and no current view set
6255
 
                self.outf.write(gettext('No current view.\n'))
 
5751
                self.outf.write('No current view.\n')
6256
5752
            else:
6257
5753
                view_str = views.view_display_str(tree.views.lookup_view(name))
6258
 
                self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
 
5754
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
6259
5755
 
6260
5756
 
6261
5757
class cmd_hooks(Command):
6275
5771
                        self.outf.write("    %s\n" %
6276
5772
                                        (some_hooks.get_hook_name(hook),))
6277
5773
                else:
6278
 
                    self.outf.write(gettext("    <no hooks installed>\n"))
 
5774
                    self.outf.write("    <no hooks installed>\n")
6279
5775
 
6280
5776
 
6281
5777
class cmd_remove_branch(Command):
6301
5797
            location = "."
6302
5798
        branch = Branch.open_containing(location)[0]
6303
5799
        branch.bzrdir.destroy_branch()
6304
 
 
 
5800
        
6305
5801
 
6306
5802
class cmd_shelve(Command):
6307
5803
    __doc__ = """Temporarily set aside some changes from the current tree.
6326
5822
 
6327
5823
    You can put multiple items on the shelf, and by default, 'unshelve' will
6328
5824
    restore the most recently shelved changes.
6329
 
 
6330
 
    For complicated changes, it is possible to edit the changes in a separate
6331
 
    editor program to decide what the file remaining in the working copy
6332
 
    should look like.  To do this, add the configuration option
6333
 
 
6334
 
        change_editor = PROGRAM @new_path @old_path
6335
 
 
6336
 
    where @new_path is replaced with the path of the new version of the 
6337
 
    file and @old_path is replaced with the path of the old version of 
6338
 
    the file.  The PROGRAM should save the new file with the desired 
6339
 
    contents of the file in the working tree.
6340
 
        
6341
5825
    """
6342
5826
 
6343
5827
    takes_args = ['file*']
6355
5839
        Option('destroy',
6356
5840
               help='Destroy removed changes instead of shelving them.'),
6357
5841
    ]
6358
 
    _see_also = ['unshelve', 'configuration']
 
5842
    _see_also = ['unshelve']
6359
5843
 
6360
5844
    def run(self, revision=None, all=False, file_list=None, message=None,
6361
 
            writer=None, list=False, destroy=False, directory=None):
 
5845
            writer=None, list=False, destroy=False, directory=u'.'):
6362
5846
        if list:
6363
 
            return self.run_for_list(directory=directory)
 
5847
            return self.run_for_list()
6364
5848
        from bzrlib.shelf_ui import Shelver
6365
5849
        if writer is None:
6366
5850
            writer = bzrlib.option.diff_writer_registry.get()
6374
5858
        except errors.UserAbort:
6375
5859
            return 0
6376
5860
 
6377
 
    def run_for_list(self, directory=None):
6378
 
        if directory is None:
6379
 
            directory = u'.'
6380
 
        tree = WorkingTree.open_containing(directory)[0]
 
5861
    def run_for_list(self):
 
5862
        tree = WorkingTree.open_containing('.')[0]
6381
5863
        self.add_cleanup(tree.lock_read().unlock)
6382
5864
        manager = tree.get_shelf_manager()
6383
5865
        shelves = manager.active_shelves()
6384
5866
        if len(shelves) == 0:
6385
 
            note(gettext('No shelved changes.'))
 
5867
            note('No shelved changes.')
6386
5868
            return 0
6387
5869
        for shelf_id in reversed(shelves):
6388
5870
            message = manager.get_metadata(shelf_id).get('message')
6442
5924
    """
6443
5925
    takes_options = ['directory',
6444
5926
                     Option('ignored', help='Delete all ignored files.'),
6445
 
                     Option('detritus', help='Delete conflict files, merge and revert'
 
5927
                     Option('detritus', help='Delete conflict files, merge'
6446
5928
                            ' backups, and failed selftest dirs.'),
6447
5929
                     Option('unknown',
6448
5930
                            help='Delete files unknown to bzr (default).'),
6477
5959
        if path is not None:
6478
5960
            branchdir = path
6479
5961
        tree, branch, relpath =(
6480
 
            controldir.ControlDir.open_containing_tree_or_branch(branchdir))
 
5962
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6481
5963
        if path is not None:
6482
5964
            path = relpath
6483
5965
        if tree is None:
6507
5989
            self.outf.write('%s %s\n' % (path, location))
6508
5990
 
6509
5991
 
6510
 
class cmd_export_pot(Command):
6511
 
    __doc__ = """Export command helps and error messages in po format."""
6512
 
 
6513
 
    hidden = True
6514
 
    takes_options = [Option('plugin', 
6515
 
                            help='Export help text from named command '\
6516
 
                                 '(defaults to all built in commands).',
6517
 
                            type=str)]
6518
 
 
6519
 
    def run(self, plugin=None):
6520
 
        from bzrlib.export_pot import export_pot
6521
 
        export_pot(self.outf, plugin)
6522
 
 
6523
 
 
6524
5992
def _register_lazy_builtins():
6525
5993
    # register lazy builtins from other modules; called at startup and should
6526
5994
    # be only called once.
6527
5995
    for (name, aliases, module_name) in [
6528
5996
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6529
 
        ('cmd_config', [], 'bzrlib.config'),
6530
5997
        ('cmd_dpush', [], 'bzrlib.foreign'),
6531
5998
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6532
5999
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6533
6000
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6534
 
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6535
 
        ('cmd_verify_signatures', [],
6536
 
                                        'bzrlib.commit_signature_commands'),
6537
 
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
 
6001
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6538
6002
        ]:
6539
6003
        builtin_command_registry.register_lazy(name, aliases, module_name)