~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Parth Malwankar
  • Date: 2010-05-03 08:33:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5210.
  • Revision ID: parth.malwankar@gmail.com-20100503083332-233xyz4wwef6x3ey
removedĀ unusedĀ import.

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
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
 
23
import codecs
23
24
import cStringIO
24
25
import sys
25
26
import time
32
33
    bzrdir,
33
34
    directory_service,
34
35
    delta,
35
 
    config as _mod_config,
 
36
    config,
36
37
    errors,
37
38
    globbing,
38
39
    hooks,
44
45
    rename_map,
45
46
    revision as _mod_revision,
46
47
    static_tuple,
 
48
    symbol_versioning,
47
49
    timestamp,
48
50
    transport,
49
51
    ui,
50
52
    urlutils,
51
53
    views,
52
 
    gpg,
53
54
    )
54
55
from bzrlib.branch import Branch
55
56
from bzrlib.conflicts import ConflictList
72
73
    _parse_revision_str,
73
74
    )
74
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
75
 
from bzrlib import (
76
 
    symbol_versioning,
77
 
    )
78
 
 
79
 
 
80
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
 
76
 
 
77
 
81
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
82
79
    apply_view=True):
83
 
    return internal_tree_files(file_list, default_branch, canonicalize,
84
 
        apply_view)
 
80
    try:
 
81
        return internal_tree_files(file_list, default_branch, canonicalize,
 
82
            apply_view)
 
83
    except errors.FileInWrongBranch, e:
 
84
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
 
85
                                     (e.path, file_list[0]))
85
86
 
86
87
 
87
88
def tree_files_for_add(file_list):
151
152
 
152
153
# XXX: Bad function name; should possibly also be a class method of
153
154
# WorkingTree rather than a function.
154
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
155
155
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
156
156
    apply_view=True):
157
157
    """Convert command-line paths to a WorkingTree and relative paths.
158
158
 
159
 
    Deprecated: use WorkingTree.open_containing_paths instead.
160
 
 
161
159
    This is typically used for command-line processors that take one or
162
160
    more filenames, and infer the workingtree that contains them.
163
161
 
173
171
 
174
172
    :return: workingtree, [relative_paths]
175
173
    """
176
 
    return WorkingTree.open_containing_paths(
177
 
        file_list, default_directory='.',
178
 
        canonicalize=True,
179
 
        apply_view=True)
 
174
    if file_list is None or len(file_list) == 0:
 
175
        tree = WorkingTree.open_containing(default_branch)[0]
 
176
        if tree.supports_views() and apply_view:
 
177
            view_files = tree.views.lookup_view()
 
178
            if view_files:
 
179
                file_list = view_files
 
180
                view_str = views.view_display_str(view_files)
 
181
                note("Ignoring files outside view. View is %s" % view_str)
 
182
        return tree, file_list
 
183
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
184
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
185
        apply_view=apply_view)
 
186
 
 
187
 
 
188
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
 
189
    """Convert file_list into a list of relpaths in tree.
 
190
 
 
191
    :param tree: A tree to operate on.
 
192
    :param file_list: A list of user provided paths or None.
 
193
    :param apply_view: if True and a view is set, apply it or check that
 
194
        specified files are within it
 
195
    :return: A list of relative paths.
 
196
    :raises errors.PathNotChild: When a provided path is in a different tree
 
197
        than tree.
 
198
    """
 
199
    if file_list is None:
 
200
        return None
 
201
    if tree.supports_views() and apply_view:
 
202
        view_files = tree.views.lookup_view()
 
203
    else:
 
204
        view_files = []
 
205
    new_list = []
 
206
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
 
207
    # doesn't - fix that up here before we enter the loop.
 
208
    if canonicalize:
 
209
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
 
210
    else:
 
211
        fixer = tree.relpath
 
212
    for filename in file_list:
 
213
        try:
 
214
            relpath = fixer(osutils.dereference_path(filename))
 
215
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
216
                raise errors.FileOutsideView(filename, view_files)
 
217
            new_list.append(relpath)
 
218
        except errors.PathNotChild:
 
219
            raise errors.FileInWrongBranch(tree.branch, filename)
 
220
    return new_list
180
221
 
181
222
 
182
223
def _get_view_info_for_change_reporter(tree):
191
232
    return view_info
192
233
 
193
234
 
194
 
def _open_directory_or_containing_tree_or_branch(filename, directory):
195
 
    """Open the tree or branch containing the specified file, unless
196
 
    the --directory option is used to specify a different branch."""
197
 
    if directory is not None:
198
 
        return (None, Branch.open(directory), filename)
199
 
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
200
 
 
201
 
 
202
235
# TODO: Make sure no commands unconditionally use the working directory as a
203
236
# branch.  If a filename argument is used, the first of them should be used to
204
237
# specify the branch.  (Perhaps this can be factored out into some kind of
253
286
    To skip the display of pending merge information altogether, use
254
287
    the no-pending option or specify a file/directory.
255
288
 
256
 
    To compare the working directory to a specific revision, pass a
257
 
    single revision to the revision argument.
258
 
 
259
 
    To see which files have changed in a specific revision, or between
260
 
    two revisions, pass a revision range to the revision argument.
261
 
    This will produce the same results as calling 'bzr diff --summarize'.
 
289
    If a revision argument is given, the status is calculated against
 
290
    that revision, or between two revisions if two are provided.
262
291
    """
263
292
 
264
293
    # TODO: --no-recurse, --recurse options
286
315
            raise errors.BzrCommandError('bzr status --revision takes exactly'
287
316
                                         ' one or two revision specifiers')
288
317
 
289
 
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
318
        tree, relfile_list = tree_files(file_list)
290
319
        # Avoid asking for specific files when that is not needed.
291
320
        if relfile_list == ['']:
292
321
            relfile_list = None
311
340
 
312
341
    hidden = True
313
342
    takes_args = ['revision_id?']
314
 
    takes_options = ['directory', 'revision']
 
343
    takes_options = ['revision']
315
344
    # cat-revision is more for frontends so should be exact
316
345
    encoding = 'strict'
317
346
 
324
353
        self.outf.write(revtext.decode('utf-8'))
325
354
 
326
355
    @display_command
327
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
356
    def run(self, revision_id=None, revision=None):
328
357
        if revision_id is not None and revision is not None:
329
358
            raise errors.BzrCommandError('You can only supply one of'
330
359
                                         ' revision_id or --revision')
331
360
        if revision_id is None and revision is None:
332
361
            raise errors.BzrCommandError('You must supply either'
333
362
                                         ' --revision or a revision_id')
334
 
 
335
 
        b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
 
363
        b = WorkingTree.open_containing(u'.')[0].branch
336
364
 
337
365
        revisions = b.repository.revisions
338
366
        if revisions is None:
416
444
                self.outf.write(page_bytes[:header_end])
417
445
                page_bytes = data
418
446
            self.outf.write('\nPage %d\n' % (page_idx,))
419
 
            if len(page_bytes) == 0:
420
 
                self.outf.write('(empty)\n');
421
 
            else:
422
 
                decomp_bytes = zlib.decompress(page_bytes)
423
 
                self.outf.write(decomp_bytes)
424
 
                self.outf.write('\n')
 
447
            decomp_bytes = zlib.decompress(page_bytes)
 
448
            self.outf.write(decomp_bytes)
 
449
            self.outf.write('\n')
425
450
 
426
451
    def _dump_entries(self, trans, basename):
427
452
        try:
458
483
    takes_options = [
459
484
        Option('force',
460
485
               help='Remove the working tree even if it has '
461
 
                    'uncommitted or shelved changes.'),
 
486
                    'uncommitted changes.'),
462
487
        ]
463
488
 
464
489
    def run(self, location_list, force=False):
478
503
            if not force:
479
504
                if (working.has_changes()):
480
505
                    raise errors.UncommittedChanges(working)
481
 
                if working.get_shelf_manager().last_shelf() is not None:
482
 
                    raise errors.ShelvedChanges(working)
483
506
 
484
507
            if working.user_url != working.branch.user_url:
485
508
                raise errors.BzrCommandError("You cannot remove the working tree"
488
511
            d.destroy_workingtree()
489
512
 
490
513
 
491
 
class cmd_repair_workingtree(Command):
492
 
    __doc__ = """Reset the working tree state file.
493
 
 
494
 
    This is not meant to be used normally, but more as a way to recover from
495
 
    filesystem corruption, etc. This rebuilds the working inventory back to a
496
 
    'known good' state. Any new modifications (adding a file, renaming, etc)
497
 
    will be lost, though modified files will still be detected as such.
498
 
 
499
 
    Most users will want something more like "bzr revert" or "bzr update"
500
 
    unless the state file has become corrupted.
501
 
 
502
 
    By default this attempts to recover the current state by looking at the
503
 
    headers of the state file. If the state file is too corrupted to even do
504
 
    that, you can supply --revision to force the state of the tree.
505
 
    """
506
 
 
507
 
    takes_options = ['revision', 'directory',
508
 
        Option('force',
509
 
               help='Reset the tree even if it doesn\'t appear to be'
510
 
                    ' corrupted.'),
511
 
    ]
512
 
    hidden = True
513
 
 
514
 
    def run(self, revision=None, directory='.', force=False):
515
 
        tree, _ = WorkingTree.open_containing(directory)
516
 
        self.add_cleanup(tree.lock_tree_write().unlock)
517
 
        if not force:
518
 
            try:
519
 
                tree.check_state()
520
 
            except errors.BzrError:
521
 
                pass # There seems to be a real error here, so we'll reset
522
 
            else:
523
 
                # Refuse
524
 
                raise errors.BzrCommandError(
525
 
                    'The tree does not appear to be corrupt. You probably'
526
 
                    ' want "bzr revert" instead. Use "--force" if you are'
527
 
                    ' sure you want to reset the working tree.')
528
 
        if revision is None:
529
 
            revision_ids = None
530
 
        else:
531
 
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
532
 
        try:
533
 
            tree.reset_state(revision_ids)
534
 
        except errors.BzrError, e:
535
 
            if revision_ids is None:
536
 
                extra = (', the header appears corrupt, try passing -r -1'
537
 
                         ' to set the state to the last commit')
538
 
            else:
539
 
                extra = ''
540
 
            raise errors.BzrCommandError('failed to reset the tree state'
541
 
                                         + extra)
542
 
 
543
 
 
544
514
class cmd_revno(Command):
545
515
    __doc__ = """Show current revision number.
546
516
 
558
528
        if tree:
559
529
            try:
560
530
                wt = WorkingTree.open_containing(location)[0]
561
 
                self.add_cleanup(wt.lock_read().unlock)
 
531
                wt.lock_read()
562
532
            except (errors.NoWorkingTree, errors.NotLocalUrl):
563
533
                raise errors.NoWorkingTree(location)
 
534
            self.add_cleanup(wt.unlock)
564
535
            revid = wt.last_revision()
565
536
            try:
566
537
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
569
540
            revno = ".".join(str(n) for n in revno_t)
570
541
        else:
571
542
            b = Branch.open_containing(location)[0]
572
 
            self.add_cleanup(b.lock_read().unlock)
 
543
            b.lock_read()
 
544
            self.add_cleanup(b.unlock)
573
545
            revno = b.revno()
574
546
        self.cleanup_now()
575
547
        self.outf.write(str(revno) + '\n')
582
554
    takes_args = ['revision_info*']
583
555
    takes_options = [
584
556
        'revision',
585
 
        custom_help('directory',
 
557
        Option('directory',
586
558
            help='Branch to examine, '
587
 
                 'rather than the one containing the working directory.'),
 
559
                 'rather than the one containing the working directory.',
 
560
            short_name='d',
 
561
            type=unicode,
 
562
            ),
588
563
        Option('tree', help='Show revno of working tree'),
589
564
        ]
590
565
 
595
570
        try:
596
571
            wt = WorkingTree.open_containing(directory)[0]
597
572
            b = wt.branch
598
 
            self.add_cleanup(wt.lock_read().unlock)
 
573
            wt.lock_read()
 
574
            self.add_cleanup(wt.unlock)
599
575
        except (errors.NoWorkingTree, errors.NotLocalUrl):
600
576
            wt = None
601
577
            b = Branch.open_containing(directory)[0]
602
 
            self.add_cleanup(b.lock_read().unlock)
 
578
            b.lock_read()
 
579
            self.add_cleanup(b.unlock)
603
580
        revision_ids = []
604
581
        if revision is not None:
605
582
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
704
681
                should_print=(not is_quiet()))
705
682
 
706
683
        if base_tree:
707
 
            self.add_cleanup(base_tree.lock_read().unlock)
 
684
            base_tree.lock_read()
 
685
            self.add_cleanup(base_tree.unlock)
708
686
        tree, file_list = tree_files_for_add(file_list)
709
687
        added, ignored = tree.smart_add(file_list, not
710
688
            no_recurse, action=action, save=not dry_run)
781
759
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
782
760
 
783
761
        revision = _get_one_revision('inventory', revision)
784
 
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
785
 
        self.add_cleanup(work_tree.lock_read().unlock)
 
762
        work_tree, file_list = tree_files(file_list)
 
763
        work_tree.lock_read()
 
764
        self.add_cleanup(work_tree.unlock)
786
765
        if revision is not None:
787
766
            tree = revision.as_tree(work_tree.branch)
788
767
 
789
768
            extra_trees = [work_tree]
790
 
            self.add_cleanup(tree.lock_read().unlock)
 
769
            tree.lock_read()
 
770
            self.add_cleanup(tree.unlock)
791
771
        else:
792
772
            tree = work_tree
793
773
            extra_trees = []
797
777
                                      require_versioned=True)
798
778
            # find_ids_across_trees may include some paths that don't
799
779
            # exist in 'tree'.
800
 
            entries = sorted(
801
 
                (tree.id2path(file_id), tree.inventory[file_id])
802
 
                for file_id in file_ids if tree.has_id(file_id))
 
780
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
781
                             for file_id in file_ids if file_id in tree)
803
782
        else:
804
783
            entries = tree.inventory.entries()
805
784
 
853
832
            names_list = []
854
833
        if len(names_list) < 2:
855
834
            raise errors.BzrCommandError("missing file argument")
856
 
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
857
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
835
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
836
        tree.lock_tree_write()
 
837
        self.add_cleanup(tree.unlock)
858
838
        self._run(tree, names_list, rel_names, after)
859
839
 
860
840
    def run_auto(self, names_list, after, dry_run):
864
844
        if after:
865
845
            raise errors.BzrCommandError('--after cannot be specified with'
866
846
                                         ' --auto.')
867
 
        work_tree, file_list = WorkingTree.open_containing_paths(
868
 
            names_list, default_directory='.')
869
 
        self.add_cleanup(work_tree.lock_tree_write().unlock)
 
847
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
848
        work_tree.lock_tree_write()
 
849
        self.add_cleanup(work_tree.unlock)
870
850
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
871
851
 
872
852
    def _run(self, tree, names_list, rel_names, after):
966
946
    match the remote one, use pull --overwrite. This will work even if the two
967
947
    branches have diverged.
968
948
 
969
 
    If there is no default location set, the first pull will set it (use
970
 
    --no-remember to avoid settting it). After that, you can omit the
971
 
    location to use the default.  To change the default, use --remember. The
972
 
    value will only be saved if the remote location can be accessed.
 
949
    If there is no default location set, the first pull will set it.  After
 
950
    that, you can omit the location to use the default.  To change the
 
951
    default, use --remember. The value will only be saved if the remote
 
952
    location can be accessed.
973
953
 
974
954
    Note: The location can be specified either in the form of a branch,
975
955
    or in the form of a path to a file containing a merge directive generated
980
960
    takes_options = ['remember', 'overwrite', 'revision',
981
961
        custom_help('verbose',
982
962
            help='Show logs of pulled revisions.'),
983
 
        custom_help('directory',
 
963
        Option('directory',
984
964
            help='Branch to pull into, '
985
 
                 'rather than the one containing the working directory.'),
 
965
                 'rather than the one containing the working directory.',
 
966
            short_name='d',
 
967
            type=unicode,
 
968
            ),
986
969
        Option('local',
987
970
            help="Perform a local pull in a bound "
988
971
                 "branch.  Local pulls are not applied to "
989
972
                 "the master branch."
990
973
            ),
991
 
        Option('show-base',
992
 
            help="Show base revision text in conflicts.")
993
974
        ]
994
975
    takes_args = ['location?']
995
976
    encoding_type = 'replace'
996
977
 
997
 
    def run(self, location=None, remember=None, overwrite=False,
 
978
    def run(self, location=None, remember=False, overwrite=False,
998
979
            revision=None, verbose=False,
999
 
            directory=None, local=False,
1000
 
            show_base=False):
 
980
            directory=None, local=False):
1001
981
        # FIXME: too much stuff is in the command class
1002
982
        revision_id = None
1003
983
        mergeable = None
1006
986
        try:
1007
987
            tree_to = WorkingTree.open_containing(directory)[0]
1008
988
            branch_to = tree_to.branch
1009
 
            self.add_cleanup(tree_to.lock_write().unlock)
 
989
            tree_to.lock_write()
 
990
            self.add_cleanup(tree_to.unlock)
1010
991
        except errors.NoWorkingTree:
1011
992
            tree_to = None
1012
993
            branch_to = Branch.open_containing(directory)[0]
1013
 
            self.add_cleanup(branch_to.lock_write().unlock)
1014
 
 
1015
 
        if tree_to is None and show_base:
1016
 
            raise errors.BzrCommandError("Need working tree for --show-base.")
 
994
            branch_to.lock_write()
 
995
            self.add_cleanup(branch_to.unlock)
1017
996
 
1018
997
        if local and not branch_to.get_bound_location():
1019
998
            raise errors.LocalRequiresBoundBranch()
1050
1029
        else:
1051
1030
            branch_from = Branch.open(location,
1052
1031
                possible_transports=possible_transports)
1053
 
            self.add_cleanup(branch_from.lock_read().unlock)
1054
 
            # Remembers if asked explicitly or no previous location is set
1055
 
            if (remember
1056
 
                or (remember is None and branch_to.get_parent() is None)):
 
1032
            branch_from.lock_read()
 
1033
            self.add_cleanup(branch_from.unlock)
 
1034
 
 
1035
            if branch_to.get_parent() is None or remember:
1057
1036
                branch_to.set_parent(branch_from.base)
1058
1037
 
1059
1038
        if revision is not None:
1066
1045
                view_info=view_info)
1067
1046
            result = tree_to.pull(
1068
1047
                branch_from, overwrite, revision_id, change_reporter,
1069
 
                possible_transports=possible_transports, local=local,
1070
 
                show_base=show_base)
 
1048
                possible_transports=possible_transports, local=local)
1071
1049
        else:
1072
1050
            result = branch_to.pull(
1073
1051
                branch_from, overwrite, revision_id, local=local)
1077
1055
            log.show_branch_change(
1078
1056
                branch_to, self.outf, result.old_revno,
1079
1057
                result.old_revid)
1080
 
        if getattr(result, 'tag_conflicts', None):
1081
 
            return 1
1082
 
        else:
1083
 
            return 0
1084
1058
 
1085
1059
 
1086
1060
class cmd_push(Command):
1103
1077
    do a merge (see bzr help merge) from the other branch, and commit that.
1104
1078
    After that you will be able to do a push without '--overwrite'.
1105
1079
 
1106
 
    If there is no default push location set, the first push will set it (use
1107
 
    --no-remember to avoid settting it).  After that, you can omit the
1108
 
    location to use the default.  To change the default, use --remember. The
1109
 
    value will only be saved if the remote location can be accessed.
 
1080
    If there is no default push location set, the first push will set it.
 
1081
    After that, you can omit the location to use the default.  To change the
 
1082
    default, use --remember. The value will only be saved if the remote
 
1083
    location can be accessed.
1110
1084
    """
1111
1085
 
1112
1086
    _see_also = ['pull', 'update', 'working-trees']
1114
1088
        Option('create-prefix',
1115
1089
               help='Create the path leading up to the branch '
1116
1090
                    'if it does not already exist.'),
1117
 
        custom_help('directory',
 
1091
        Option('directory',
1118
1092
            help='Branch to push from, '
1119
 
                 'rather than the one containing the working directory.'),
 
1093
                 'rather than the one containing the working directory.',
 
1094
            short_name='d',
 
1095
            type=unicode,
 
1096
            ),
1120
1097
        Option('use-existing-dir',
1121
1098
               help='By default push will fail if the target'
1122
1099
                    ' directory exists, but does not already'
1133
1110
        Option('strict',
1134
1111
               help='Refuse to push if there are uncommitted changes in'
1135
1112
               ' the working tree, --no-strict disables the check.'),
1136
 
        Option('no-tree',
1137
 
               help="Don't populate the working tree, even for protocols"
1138
 
               " that support it."),
1139
1113
        ]
1140
1114
    takes_args = ['location?']
1141
1115
    encoding_type = 'replace'
1142
1116
 
1143
 
    def run(self, location=None, remember=None, overwrite=False,
 
1117
    def run(self, location=None, remember=False, overwrite=False,
1144
1118
        create_prefix=False, verbose=False, revision=None,
1145
1119
        use_existing_dir=False, directory=None, stacked_on=None,
1146
 
        stacked=False, strict=None, no_tree=False):
 
1120
        stacked=False, strict=None):
1147
1121
        from bzrlib.push import _show_push_branch
1148
1122
 
1149
1123
        if directory is None:
1195
1169
        _show_push_branch(br_from, revision_id, location, self.outf,
1196
1170
            verbose=verbose, overwrite=overwrite, remember=remember,
1197
1171
            stacked_on=stacked_on, create_prefix=create_prefix,
1198
 
            use_existing_dir=use_existing_dir, no_tree=no_tree)
 
1172
            use_existing_dir=use_existing_dir)
1199
1173
 
1200
1174
 
1201
1175
class cmd_branch(Command):
1210
1184
 
1211
1185
    To retrieve the branch as of a particular revision, supply the --revision
1212
1186
    parameter, as in "branch foo/bar -r 5".
1213
 
 
1214
 
    The synonyms 'clone' and 'get' for this command are deprecated.
1215
1187
    """
1216
1188
 
1217
1189
    _see_also = ['checkout']
1218
1190
    takes_args = ['from_location', 'to_location?']
1219
 
    takes_options = ['revision',
1220
 
        Option('hardlink', help='Hard-link working tree files where possible.'),
1221
 
        Option('files-from', type=str,
1222
 
               help="Get file contents from this tree."),
 
1191
    takes_options = ['revision', Option('hardlink',
 
1192
        help='Hard-link working tree files where possible.'),
1223
1193
        Option('no-tree',
1224
1194
            help="Create a branch without a working-tree."),
1225
1195
        Option('switch',
1243
1213
 
1244
1214
    def run(self, from_location, to_location=None, revision=None,
1245
1215
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1246
 
            use_existing_dir=False, switch=False, bind=False,
1247
 
            files_from=None):
 
1216
            use_existing_dir=False, switch=False, bind=False):
1248
1217
        from bzrlib import switch as _mod_switch
1249
1218
        from bzrlib.tag import _merge_tags_if_possible
1250
 
        if self.invoked_as in ['get', 'clone']:
1251
 
            ui.ui_factory.show_user_warning(
1252
 
                'deprecated_command',
1253
 
                deprecated_name=self.invoked_as,
1254
 
                recommended_name='branch',
1255
 
                deprecated_in_version='2.4')
1256
1219
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1257
1220
            from_location)
1258
 
        if not (hardlink or files_from):
1259
 
            # accelerator_tree is usually slower because you have to read N
1260
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1261
 
            # explicitly request it
1262
 
            accelerator_tree = None
1263
 
        if files_from is not None and files_from != from_location:
1264
 
            accelerator_tree = WorkingTree.open(files_from)
1265
1221
        revision = _get_one_revision('branch', revision)
1266
 
        self.add_cleanup(br_from.lock_read().unlock)
 
1222
        br_from.lock_read()
 
1223
        self.add_cleanup(br_from.unlock)
1267
1224
        if revision is not None:
1268
1225
            revision_id = revision.as_revision_id(br_from)
1269
1226
        else:
1374
1331
            to_location = branch_location
1375
1332
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1376
1333
            branch_location)
1377
 
        if not (hardlink or files_from):
1378
 
            # accelerator_tree is usually slower because you have to read N
1379
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1380
 
            # explicitly request it
1381
 
            accelerator_tree = None
1382
1334
        revision = _get_one_revision('checkout', revision)
1383
 
        if files_from is not None and files_from != branch_location:
 
1335
        if files_from is not None:
1384
1336
            accelerator_tree = WorkingTree.open(files_from)
1385
1337
        if revision is not None:
1386
1338
            revision_id = revision.as_revision_id(source)
1398
1350
            except errors.NoWorkingTree:
1399
1351
                source.bzrdir.create_workingtree(revision_id)
1400
1352
                return
 
1353
 
 
1354
        if not lightweight:
 
1355
            message = ('Copying history to "%s". '
 
1356
                'This may take some time.' % to_location)
 
1357
            ui.ui_factory.show_message(message)
1401
1358
        source.create_checkout(to_location, revision_id, lightweight,
1402
1359
                               accelerator_tree, hardlink)
1403
1360
 
1414
1371
    @display_command
1415
1372
    def run(self, dir=u'.'):
1416
1373
        tree = WorkingTree.open_containing(dir)[0]
1417
 
        self.add_cleanup(tree.lock_read().unlock)
 
1374
        tree.lock_read()
 
1375
        self.add_cleanup(tree.unlock)
1418
1376
        new_inv = tree.inventory
1419
1377
        old_tree = tree.basis_tree()
1420
 
        self.add_cleanup(old_tree.lock_read().unlock)
 
1378
        old_tree.lock_read()
 
1379
        self.add_cleanup(old_tree.unlock)
1421
1380
        old_inv = old_tree.inventory
1422
1381
        renames = []
1423
1382
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1442
1401
    If you want to discard your local changes, you can just do a
1443
1402
    'bzr revert' instead of 'bzr commit' after the update.
1444
1403
 
1445
 
    If you want to restore a file that has been removed locally, use
1446
 
    'bzr revert' instead of 'bzr update'.
1447
 
 
1448
1404
    If the tree's branch is bound to a master branch, it will also update
1449
1405
    the branch from the master.
1450
1406
    """
1451
1407
 
1452
1408
    _see_also = ['pull', 'working-trees', 'status-flags']
1453
1409
    takes_args = ['dir?']
1454
 
    takes_options = ['revision',
1455
 
                     Option('show-base',
1456
 
                            help="Show base revision text in conflicts."),
1457
 
                     ]
 
1410
    takes_options = ['revision']
1458
1411
    aliases = ['up']
1459
1412
 
1460
 
    def run(self, dir='.', revision=None, show_base=None):
 
1413
    def run(self, dir='.', revision=None):
1461
1414
        if revision is not None and len(revision) != 1:
1462
1415
            raise errors.BzrCommandError(
1463
1416
                        "bzr update --revision takes exactly one revision")
1467
1420
        master = branch.get_master_branch(
1468
1421
            possible_transports=possible_transports)
1469
1422
        if master is not None:
 
1423
            tree.lock_write()
1470
1424
            branch_location = master.base
1471
 
            tree.lock_write()
1472
1425
        else:
 
1426
            tree.lock_tree_write()
1473
1427
            branch_location = tree.branch.base
1474
 
            tree.lock_tree_write()
1475
1428
        self.add_cleanup(tree.unlock)
1476
1429
        # get rid of the final '/' and be ready for display
1477
1430
        branch_location = urlutils.unescape_for_display(
1503
1456
                change_reporter,
1504
1457
                possible_transports=possible_transports,
1505
1458
                revision=revision_id,
1506
 
                old_tip=old_tip,
1507
 
                show_base=show_base)
 
1459
                old_tip=old_tip)
1508
1460
        except errors.NoSuchRevision, e:
1509
1461
            raise errors.BzrCommandError(
1510
1462
                                  "branch has no revision %s\n"
1572
1524
class cmd_remove(Command):
1573
1525
    __doc__ = """Remove files or directories.
1574
1526
 
1575
 
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1576
 
    delete them if they can easily be recovered using revert otherwise they
1577
 
    will be backed up (adding an extention of the form .~#~). If no options or
1578
 
    parameters are given Bazaar will scan for files that are being tracked by
1579
 
    Bazaar but missing in your tree and stop tracking them for you.
 
1527
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1528
    them if they can easily be recovered using revert. If no options or
 
1529
    parameters are given bzr will scan for files that are being tracked by bzr
 
1530
    but missing in your tree and stop tracking them for you.
1580
1531
    """
1581
1532
    takes_args = ['file*']
1582
1533
    takes_options = ['verbose',
1584
1535
        RegistryOption.from_kwargs('file-deletion-strategy',
1585
1536
            'The file deletion mode to be used.',
1586
1537
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1587
 
            safe='Backup changed files (default).',
 
1538
            safe='Only delete files if they can be'
 
1539
                 ' safely recovered (default).',
1588
1540
            keep='Delete from bzr but leave the working copy.',
1589
 
            no_backup='Don\'t backup changed files.',
1590
1541
            force='Delete all the specified files, even if they can not be '
1591
 
                'recovered and even if they are non-empty directories. '
1592
 
                '(deprecated, use no-backup)')]
 
1542
                'recovered and even if they are non-empty directories.')]
1593
1543
    aliases = ['rm', 'del']
1594
1544
    encoding_type = 'replace'
1595
1545
 
1596
1546
    def run(self, file_list, verbose=False, new=False,
1597
1547
        file_deletion_strategy='safe'):
1598
 
        if file_deletion_strategy == 'force':
1599
 
            note("(The --force option is deprecated, rather use --no-backup "
1600
 
                "in future.)")
1601
 
            file_deletion_strategy = 'no-backup'
1602
 
 
1603
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1548
        tree, file_list = tree_files(file_list)
1604
1549
 
1605
1550
        if file_list is not None:
1606
1551
            file_list = [f for f in file_list]
1607
1552
 
1608
 
        self.add_cleanup(tree.lock_write().unlock)
 
1553
        tree.lock_write()
 
1554
        self.add_cleanup(tree.unlock)
1609
1555
        # Heuristics should probably all move into tree.remove_smart or
1610
1556
        # some such?
1611
1557
        if new:
1626
1572
            file_deletion_strategy = 'keep'
1627
1573
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1628
1574
            keep_files=file_deletion_strategy=='keep',
1629
 
            force=(file_deletion_strategy=='no-backup'))
 
1575
            force=file_deletion_strategy=='force')
1630
1576
 
1631
1577
 
1632
1578
class cmd_file_id(Command):
1694
1640
 
1695
1641
    _see_also = ['check']
1696
1642
    takes_args = ['branch?']
1697
 
    takes_options = [
1698
 
        Option('canonicalize-chks',
1699
 
               help='Make sure CHKs are in canonical form (repairs '
1700
 
                    'bug 522637).',
1701
 
               hidden=True),
1702
 
        ]
1703
1643
 
1704
 
    def run(self, branch=".", canonicalize_chks=False):
 
1644
    def run(self, branch="."):
1705
1645
        from bzrlib.reconcile import reconcile
1706
1646
        dir = bzrdir.BzrDir.open(branch)
1707
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1647
        reconcile(dir)
1708
1648
 
1709
1649
 
1710
1650
class cmd_revision_history(Command):
1742
1682
            b = wt.branch
1743
1683
            last_revision = wt.last_revision()
1744
1684
 
1745
 
        self.add_cleanup(b.repository.lock_read().unlock)
1746
 
        graph = b.repository.get_graph()
1747
 
        revisions = [revid for revid, parents in
1748
 
            graph.iter_ancestry([last_revision])]
1749
 
        for revision_id in reversed(revisions):
1750
 
            if _mod_revision.is_null(revision_id):
1751
 
                continue
 
1685
        revision_ids = b.repository.get_ancestry(last_revision)
 
1686
        revision_ids.pop(0)
 
1687
        for revision_id in revision_ids:
1752
1688
            self.outf.write(revision_id + '\n')
1753
1689
 
1754
1690
 
1791
1727
                ),
1792
1728
         Option('append-revisions-only',
1793
1729
                help='Never change revnos or the existing log.'
1794
 
                '  Append revisions to it only.'),
1795
 
         Option('no-tree',
1796
 
                'Create a branch without a working tree.')
 
1730
                '  Append revisions to it only.')
1797
1731
         ]
1798
1732
    def run(self, location=None, format=None, append_revisions_only=False,
1799
 
            create_prefix=False, no_tree=False):
 
1733
            create_prefix=False):
1800
1734
        if format is None:
1801
1735
            format = bzrdir.format_registry.make_bzrdir('default')
1802
1736
        if location is None:
1825
1759
        except errors.NotBranchError:
1826
1760
            # really a NotBzrDir error...
1827
1761
            create_branch = bzrdir.BzrDir.create_branch_convenience
1828
 
            if no_tree:
1829
 
                force_new_tree = False
1830
 
            else:
1831
 
                force_new_tree = None
1832
1762
            branch = create_branch(to_transport.base, format=format,
1833
 
                                   possible_transports=[to_transport],
1834
 
                                   force_new_tree=force_new_tree)
 
1763
                                   possible_transports=[to_transport])
1835
1764
            a_bzrdir = branch.bzrdir
1836
1765
        else:
1837
1766
            from bzrlib.transport.local import LocalTransport
1841
1770
                        raise errors.BranchExistsWithoutWorkingTree(location)
1842
1771
                raise errors.AlreadyBranchError(location)
1843
1772
            branch = a_bzrdir.create_branch()
1844
 
            if not no_tree:
1845
 
                a_bzrdir.create_workingtree()
 
1773
            a_bzrdir.create_workingtree()
1846
1774
        if append_revisions_only:
1847
1775
            try:
1848
1776
                branch.set_append_revisions_only(True)
1942
1870
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1943
1871
    produces patches suitable for "patch -p1".
1944
1872
 
1945
 
    Note that when using the -r argument with a range of revisions, the
1946
 
    differences are computed between the two specified revisions.  That
1947
 
    is, the command does not show the changes introduced by the first 
1948
 
    revision in the range.  This differs from the interpretation of 
1949
 
    revision ranges used by "bzr log" which includes the first revision
1950
 
    in the range.
1951
 
 
1952
1873
    :Exit values:
1953
1874
        1 - changed
1954
1875
        2 - unrepresentable changes
1972
1893
 
1973
1894
            bzr diff -r1..3 xxx
1974
1895
 
1975
 
        The changes introduced by revision 2 (equivalent to -r1..2)::
1976
 
 
1977
 
            bzr diff -c2
1978
 
 
1979
 
        To see the changes introduced by revision X::
 
1896
        To see the changes introduced in revision X::
1980
1897
        
1981
1898
            bzr diff -cX
1982
1899
 
1986
1903
 
1987
1904
            bzr diff -r<chosen_parent>..X
1988
1905
 
1989
 
        The changes between the current revision and the previous revision
1990
 
        (equivalent to -c-1 and -r-2..-1)
 
1906
        The changes introduced by revision 2 (equivalent to -r1..2)::
1991
1907
 
1992
 
            bzr diff -r-2..
 
1908
            bzr diff -c2
1993
1909
 
1994
1910
        Show just the differences for file NEWS::
1995
1911
 
2010
1926
        Same as 'bzr diff' but prefix paths with old/ and new/::
2011
1927
 
2012
1928
            bzr diff --prefix old/:new/
2013
 
            
2014
 
        Show the differences using a custom diff program with options::
2015
 
        
2016
 
            bzr diff --using /usr/bin/diff --diff-options -wu
2017
1929
    """
2018
1930
    _see_also = ['status']
2019
1931
    takes_args = ['file*']
2039
1951
            type=unicode,
2040
1952
            ),
2041
1953
        RegistryOption('format',
2042
 
            short_name='F',
2043
1954
            help='Diff format to use.',
2044
1955
            lazy_registry=('bzrlib.diff', 'format_registry'),
2045
 
            title='Diff format'),
 
1956
            value_switches=False, title='Diff format'),
2046
1957
        ]
2047
1958
    aliases = ['di', 'dif']
2048
1959
    encoding_type = 'exact'
2079
1990
         old_branch, new_branch,
2080
1991
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
2081
1992
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
2082
 
        # GNU diff on Windows uses ANSI encoding for filenames
2083
 
        path_encoding = osutils.get_diff_header_encoding()
2084
1993
        return show_diff_trees(old_tree, new_tree, sys.stdout,
2085
1994
                               specific_files=specific_files,
2086
1995
                               external_diff_options=diff_options,
2087
1996
                               old_label=old_label, new_label=new_label,
2088
 
                               extra_trees=extra_trees,
2089
 
                               path_encoding=path_encoding,
2090
 
                               using=using,
 
1997
                               extra_trees=extra_trees, using=using,
2091
1998
                               format_cls=format)
2092
1999
 
2093
2000
 
2101
2008
    # level of effort but possibly much less IO.  (Or possibly not,
2102
2009
    # if the directories are very large...)
2103
2010
    _see_also = ['status', 'ls']
2104
 
    takes_options = ['directory', 'show-ids']
 
2011
    takes_options = ['show-ids']
2105
2012
 
2106
2013
    @display_command
2107
 
    def run(self, show_ids=False, directory=u'.'):
2108
 
        tree = WorkingTree.open_containing(directory)[0]
2109
 
        self.add_cleanup(tree.lock_read().unlock)
 
2014
    def run(self, show_ids=False):
 
2015
        tree = WorkingTree.open_containing(u'.')[0]
 
2016
        tree.lock_read()
 
2017
        self.add_cleanup(tree.unlock)
2110
2018
        old = tree.basis_tree()
2111
 
        self.add_cleanup(old.lock_read().unlock)
 
2019
        old.lock_read()
 
2020
        self.add_cleanup(old.unlock)
2112
2021
        for path, ie in old.inventory.iter_entries():
2113
2022
            if not tree.has_id(ie.file_id):
2114
2023
                self.outf.write(path)
2124
2033
 
2125
2034
    hidden = True
2126
2035
    _see_also = ['status', 'ls']
2127
 
    takes_options = ['directory', 'null']
 
2036
    takes_options = [
 
2037
            Option('null',
 
2038
                   help='Write an ascii NUL (\\0) separator '
 
2039
                   'between files rather than a newline.')
 
2040
            ]
2128
2041
 
2129
2042
    @display_command
2130
 
    def run(self, null=False, directory=u'.'):
2131
 
        tree = WorkingTree.open_containing(directory)[0]
2132
 
        self.add_cleanup(tree.lock_read().unlock)
 
2043
    def run(self, null=False):
 
2044
        tree = WorkingTree.open_containing(u'.')[0]
2133
2045
        td = tree.changes_from(tree.basis_tree())
2134
 
        self.cleanup_now()
2135
2046
        for path, id, kind, text_modified, meta_modified in td.modified:
2136
2047
            if null:
2137
2048
                self.outf.write(path + '\0')
2145
2056
 
2146
2057
    hidden = True
2147
2058
    _see_also = ['status', 'ls']
2148
 
    takes_options = ['directory', 'null']
 
2059
    takes_options = [
 
2060
            Option('null',
 
2061
                   help='Write an ascii NUL (\\0) separator '
 
2062
                   'between files rather than a newline.')
 
2063
            ]
2149
2064
 
2150
2065
    @display_command
2151
 
    def run(self, null=False, directory=u'.'):
2152
 
        wt = WorkingTree.open_containing(directory)[0]
2153
 
        self.add_cleanup(wt.lock_read().unlock)
 
2066
    def run(self, null=False):
 
2067
        wt = WorkingTree.open_containing(u'.')[0]
 
2068
        wt.lock_read()
 
2069
        self.add_cleanup(wt.unlock)
2154
2070
        basis = wt.basis_tree()
2155
 
        self.add_cleanup(basis.lock_read().unlock)
 
2071
        basis.lock_read()
 
2072
        self.add_cleanup(basis.unlock)
2156
2073
        basis_inv = basis.inventory
2157
2074
        inv = wt.inventory
2158
2075
        for file_id in inv:
2159
 
            if basis_inv.has_id(file_id):
 
2076
            if file_id in basis_inv:
2160
2077
                continue
2161
2078
            if inv.is_root(file_id) and len(basis_inv) == 0:
2162
2079
                continue
2163
2080
            path = inv.id2path(file_id)
2164
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
 
2081
            if not os.access(osutils.abspath(path), os.F_OK):
2165
2082
                continue
2166
2083
            if null:
2167
2084
                self.outf.write(path + '\0')
2367
2284
                   help='Show just the specified revision.'
2368
2285
                   ' See also "help revisionspec".'),
2369
2286
            'log-format',
2370
 
            RegistryOption('authors',
2371
 
                'What names to list as authors - first, all or committer.',
2372
 
                title='Authors',
2373
 
                lazy_registry=('bzrlib.log', 'author_list_registry'),
2374
 
            ),
2375
2287
            Option('levels',
2376
2288
                   short_name='n',
2377
2289
                   help='Number of levels to display - 0 for all, 1 for flat.',
2395
2307
            Option('exclude-common-ancestry',
2396
2308
                   help='Display only the revisions that are not part'
2397
2309
                   ' of both ancestries (require -rX..Y)'
2398
 
                   ),
2399
 
            Option('signatures',
2400
 
                   help='Show digital signature validity'),
 
2310
                   )
2401
2311
            ]
2402
2312
    encoding_type = 'replace'
2403
2313
 
2414
2324
            limit=None,
2415
2325
            show_diff=False,
2416
2326
            include_merges=False,
2417
 
            authors=None,
2418
2327
            exclude_common_ancestry=False,
2419
 
            signatures=False,
2420
2328
            ):
2421
2329
        from bzrlib.log import (
2422
2330
            Logger,
2449
2357
        if file_list:
2450
2358
            # find the file ids to log and check for directory filtering
2451
2359
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2452
 
                revision, file_list, self.add_cleanup)
 
2360
                revision, file_list)
 
2361
            self.add_cleanup(b.unlock)
2453
2362
            for relpath, file_id, kind in file_info_list:
2454
2363
                if file_id is None:
2455
2364
                    raise errors.BzrCommandError(
2473
2382
                location = '.'
2474
2383
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2475
2384
            b = dir.open_branch()
2476
 
            self.add_cleanup(b.lock_read().unlock)
 
2385
            b.lock_read()
 
2386
            self.add_cleanup(b.unlock)
2477
2387
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2478
2388
 
2479
 
        if b.get_config().validate_signatures_in_log():
2480
 
            signatures = True
2481
 
 
2482
 
        if signatures:
2483
 
            if not gpg.GPGStrategy.verify_signatures_available():
2484
 
                raise errors.GpgmeNotInstalled(None)
2485
 
 
2486
2389
        # Decide on the type of delta & diff filtering to use
2487
2390
        # TODO: add an --all-files option to make this configurable & consistent
2488
2391
        if not verbose:
2506
2409
                        show_timezone=timezone,
2507
2410
                        delta_format=get_verbosity_level(),
2508
2411
                        levels=levels,
2509
 
                        show_advice=levels is None,
2510
 
                        author_list_handler=authors)
 
2412
                        show_advice=levels is None)
2511
2413
 
2512
2414
        # Choose the algorithm for doing the logging. It's annoying
2513
2415
        # having multiple code paths like this but necessary until
2534
2436
            message_search=message, delta_type=delta_type,
2535
2437
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2536
2438
            exclude_common_ancestry=exclude_common_ancestry,
2537
 
            signature=signatures
2538
2439
            )
2539
2440
        Logger(b, rqst).show(lf)
2540
2441
 
2612
2513
        tree, relpath = WorkingTree.open_containing(filename)
2613
2514
        file_id = tree.path2id(relpath)
2614
2515
        b = tree.branch
2615
 
        self.add_cleanup(b.lock_read().unlock)
 
2516
        b.lock_read()
 
2517
        self.add_cleanup(b.unlock)
2616
2518
        touching_revs = log.find_touching_revisions(b, file_id)
2617
2519
        for revno, revision_id, what in touching_revs:
2618
2520
            self.outf.write("%6d %s\n" % (revno, what))
2631
2533
                   help='Recurse into subdirectories.'),
2632
2534
            Option('from-root',
2633
2535
                   help='Print paths relative to the root of the branch.'),
2634
 
            Option('unknown', short_name='u',
2635
 
                help='Print unknown files.'),
 
2536
            Option('unknown', help='Print unknown files.'),
2636
2537
            Option('versioned', help='Print versioned files.',
2637
2538
                   short_name='V'),
2638
 
            Option('ignored', short_name='i',
2639
 
                help='Print ignored files.'),
2640
 
            Option('kind', short_name='k',
 
2539
            Option('ignored', help='Print ignored files.'),
 
2540
            Option('null',
 
2541
                   help='Write an ascii NUL (\\0) separator '
 
2542
                   'between files rather than a newline.'),
 
2543
            Option('kind',
2641
2544
                   help='List entries of a particular kind: file, directory, symlink.',
2642
2545
                   type=unicode),
2643
 
            'null',
2644
2546
            'show-ids',
2645
 
            'directory',
2646
2547
            ]
2647
2548
    @display_command
2648
2549
    def run(self, revision=None, verbose=False,
2649
2550
            recursive=False, from_root=False,
2650
2551
            unknown=False, versioned=False, ignored=False,
2651
 
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2552
            null=False, kind=None, show_ids=False, path=None):
2652
2553
 
2653
2554
        if kind and kind not in ('file', 'directory', 'symlink'):
2654
2555
            raise errors.BzrCommandError('invalid kind specified')
2666
2567
                raise errors.BzrCommandError('cannot specify both --from-root'
2667
2568
                                             ' and PATH')
2668
2569
            fs_path = path
2669
 
        tree, branch, relpath = \
2670
 
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2570
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2571
            fs_path)
2671
2572
 
2672
2573
        # Calculate the prefix to use
2673
2574
        prefix = None
2688
2589
                view_str = views.view_display_str(view_files)
2689
2590
                note("Ignoring files outside view. View is %s" % view_str)
2690
2591
 
2691
 
        self.add_cleanup(tree.lock_read().unlock)
 
2592
        tree.lock_read()
 
2593
        self.add_cleanup(tree.unlock)
2692
2594
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2693
2595
            from_dir=relpath, recursive=recursive):
2694
2596
            # Apply additional masking
2741
2643
 
2742
2644
    hidden = True
2743
2645
    _see_also = ['ls']
2744
 
    takes_options = ['directory']
2745
2646
 
2746
2647
    @display_command
2747
 
    def run(self, directory=u'.'):
2748
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
2648
    def run(self):
 
2649
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
2749
2650
            self.outf.write(osutils.quotefn(f) + '\n')
2750
2651
 
2751
2652
 
2778
2679
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2779
2680
    precedence over the '!' exception patterns.
2780
2681
 
2781
 
    :Notes: 
2782
 
        
2783
 
    * Ignore patterns containing shell wildcards must be quoted from
2784
 
      the shell on Unix.
2785
 
 
2786
 
    * Ignore patterns starting with "#" act as comments in the ignore file.
2787
 
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
2682
    Note: ignore patterns containing shell wildcards must be quoted from
 
2683
    the shell on Unix.
2788
2684
 
2789
2685
    :Examples:
2790
2686
        Ignore the top level Makefile::
2799
2695
 
2800
2696
            bzr ignore "!special.class"
2801
2697
 
2802
 
        Ignore files whose name begins with the "#" character::
2803
 
 
2804
 
            bzr ignore "RE:^#"
2805
 
 
2806
2698
        Ignore .o files under the lib directory::
2807
2699
 
2808
2700
            bzr ignore "lib/**/*.o"
2816
2708
            bzr ignore "RE:(?!debian/).*"
2817
2709
        
2818
2710
        Ignore everything except the "local" toplevel directory,
2819
 
        but always ignore autosave files ending in ~, even under local/::
 
2711
        but always ignore "*~" autosave files, even under local/::
2820
2712
        
2821
2713
            bzr ignore "*"
2822
2714
            bzr ignore "!./local"
2825
2717
 
2826
2718
    _see_also = ['status', 'ignored', 'patterns']
2827
2719
    takes_args = ['name_pattern*']
2828
 
    takes_options = ['directory',
 
2720
    takes_options = [
2829
2721
        Option('default-rules',
2830
2722
               help='Display the default ignore rules that bzr uses.')
2831
2723
        ]
2832
2724
 
2833
 
    def run(self, name_pattern_list=None, default_rules=None,
2834
 
            directory=u'.'):
 
2725
    def run(self, name_pattern_list=None, default_rules=None):
2835
2726
        from bzrlib import ignores
2836
2727
        if default_rules is not None:
2837
2728
            # dump the default rules and exit
2843
2734
                "NAME_PATTERN or --default-rules.")
2844
2735
        name_pattern_list = [globbing.normalize_pattern(p)
2845
2736
                             for p in name_pattern_list]
2846
 
        bad_patterns = ''
2847
 
        for p in name_pattern_list:
2848
 
            if not globbing.Globster.is_pattern_valid(p):
2849
 
                bad_patterns += ('\n  %s' % p)
2850
 
        if bad_patterns:
2851
 
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2852
 
            ui.ui_factory.show_error(msg)
2853
 
            raise errors.InvalidPattern('')
2854
2737
        for name_pattern in name_pattern_list:
2855
2738
            if (name_pattern[0] == '/' or
2856
2739
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2857
2740
                raise errors.BzrCommandError(
2858
2741
                    "NAME_PATTERN should not be an absolute path")
2859
 
        tree, relpath = WorkingTree.open_containing(directory)
 
2742
        tree, relpath = WorkingTree.open_containing(u'.')
2860
2743
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2861
2744
        ignored = globbing.Globster(name_pattern_list)
2862
2745
        matches = []
2863
 
        self.add_cleanup(tree.lock_read().unlock)
 
2746
        tree.lock_read()
2864
2747
        for entry in tree.list_files():
2865
2748
            id = entry[3]
2866
2749
            if id is not None:
2867
2750
                filename = entry[0]
2868
2751
                if ignored.match(filename):
2869
2752
                    matches.append(filename)
 
2753
        tree.unlock()
2870
2754
        if len(matches) > 0:
2871
2755
            self.outf.write("Warning: the following files are version controlled and"
2872
2756
                  " match your ignore pattern:\n%s"
2887
2771
 
2888
2772
    encoding_type = 'replace'
2889
2773
    _see_also = ['ignore', 'ls']
2890
 
    takes_options = ['directory']
2891
2774
 
2892
2775
    @display_command
2893
 
    def run(self, directory=u'.'):
2894
 
        tree = WorkingTree.open_containing(directory)[0]
2895
 
        self.add_cleanup(tree.lock_read().unlock)
 
2776
    def run(self):
 
2777
        tree = WorkingTree.open_containing(u'.')[0]
 
2778
        tree.lock_read()
 
2779
        self.add_cleanup(tree.unlock)
2896
2780
        for path, file_class, kind, file_id, entry in tree.list_files():
2897
2781
            if file_class != 'I':
2898
2782
                continue
2909
2793
    """
2910
2794
    hidden = True
2911
2795
    takes_args = ['revno']
2912
 
    takes_options = ['directory']
2913
2796
 
2914
2797
    @display_command
2915
 
    def run(self, revno, directory=u'.'):
 
2798
    def run(self, revno):
2916
2799
        try:
2917
2800
            revno = int(revno)
2918
2801
        except ValueError:
2919
2802
            raise errors.BzrCommandError("not a valid revision-number: %r"
2920
2803
                                         % revno)
2921
 
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
 
2804
        revid = WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2922
2805
        self.outf.write("%s\n" % revid)
2923
2806
 
2924
2807
 
2950
2833
         zip                          .zip
2951
2834
      =================       =========================
2952
2835
    """
2953
 
    encoding = 'exact'
2954
2836
    takes_args = ['dest', 'branch_or_subdir?']
2955
 
    takes_options = ['directory',
 
2837
    takes_options = [
2956
2838
        Option('format',
2957
2839
               help="Type of file to export to.",
2958
2840
               type=unicode),
2967
2849
                    'revision in which it was changed.'),
2968
2850
        ]
2969
2851
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2970
 
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
 
2852
        root=None, filters=False, per_file_timestamps=False):
2971
2853
        from bzrlib.export import export
2972
2854
 
2973
2855
        if branch_or_subdir is None:
2974
 
            tree = WorkingTree.open_containing(directory)[0]
 
2856
            tree = WorkingTree.open_containing(u'.')[0]
2975
2857
            b = tree.branch
2976
2858
            subdir = None
2977
2859
        else:
2996
2878
    """
2997
2879
 
2998
2880
    _see_also = ['ls']
2999
 
    takes_options = ['directory',
 
2881
    takes_options = [
3000
2882
        Option('name-from-revision', help='The path name in the old tree.'),
3001
2883
        Option('filters', help='Apply content filters to display the '
3002
2884
                'convenience form.'),
3007
2889
 
3008
2890
    @display_command
3009
2891
    def run(self, filename, revision=None, name_from_revision=False,
3010
 
            filters=False, directory=None):
 
2892
            filters=False):
3011
2893
        if revision is not None and len(revision) != 1:
3012
2894
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
3013
2895
                                         " one revision specifier")
3014
2896
        tree, branch, relpath = \
3015
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
3016
 
        self.add_cleanup(branch.lock_read().unlock)
 
2897
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2898
        branch.lock_read()
 
2899
        self.add_cleanup(branch.unlock)
3017
2900
        return self._run(tree, branch, relpath, filename, revision,
3018
2901
                         name_from_revision, filters)
3019
2902
 
3022
2905
        if tree is None:
3023
2906
            tree = b.basis_tree()
3024
2907
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3025
 
        self.add_cleanup(rev_tree.lock_read().unlock)
 
2908
        rev_tree.lock_read()
 
2909
        self.add_cleanup(rev_tree.unlock)
3026
2910
 
3027
2911
        old_file_id = rev_tree.path2id(relpath)
3028
2912
 
3134
3018
      to trigger updates to external systems like bug trackers. The --fixes
3135
3019
      option can be used to record the association between a revision and
3136
3020
      one or more bugs. See ``bzr help bugs`` for details.
 
3021
 
 
3022
      A selective commit may fail in some cases where the committed
 
3023
      tree would be invalid. Consider::
 
3024
  
 
3025
        bzr init foo
 
3026
        mkdir foo/bar
 
3027
        bzr add foo/bar
 
3028
        bzr commit foo -m "committing foo"
 
3029
        bzr mv foo/bar foo/baz
 
3030
        mkdir foo/bar
 
3031
        bzr add foo/bar
 
3032
        bzr commit foo/bar -m "committing bar but not baz"
 
3033
  
 
3034
      In the example above, the last commit will fail by design. This gives
 
3035
      the user the opportunity to decide whether they want to commit the
 
3036
      rename at the same time, separately first, or not at all. (As a general
 
3037
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
3137
3038
    """
 
3039
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
3040
 
 
3041
    # TODO: Strict commit that fails if there are deleted files.
 
3042
    #       (what does "deleted files" mean ??)
 
3043
 
 
3044
    # TODO: Give better message for -s, --summary, used by tla people
 
3045
 
 
3046
    # XXX: verbose currently does nothing
3138
3047
 
3139
3048
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
3140
3049
    takes_args = ['selected*']
3172
3081
             Option('show-diff', short_name='p',
3173
3082
                    help='When no message is supplied, show the diff along'
3174
3083
                    ' with the status summary in the message editor.'),
3175
 
             Option('lossy', 
3176
 
                    help='When committing to a foreign version control '
3177
 
                    'system do not push data that can not be natively '
3178
 
                    'represented.'),
3179
3084
             ]
3180
3085
    aliases = ['ci', 'checkin']
3181
3086
 
3200
3105
 
3201
3106
    def run(self, message=None, file=None, verbose=False, selected_list=None,
3202
3107
            unchanged=False, strict=False, local=False, fixes=None,
3203
 
            author=None, show_diff=False, exclude=None, commit_time=None,
3204
 
            lossy=False):
 
3108
            author=None, show_diff=False, exclude=None, commit_time=None):
3205
3109
        from bzrlib.errors import (
3206
3110
            PointlessCommit,
3207
3111
            ConflictsInTree,
3210
3114
        from bzrlib.msgeditor import (
3211
3115
            edit_commit_message_encoded,
3212
3116
            generate_commit_message_template,
3213
 
            make_commit_message_template_encoded,
3214
 
            set_commit_message,
 
3117
            make_commit_message_template_encoded
3215
3118
        )
3216
3119
 
3217
3120
        commit_stamp = offset = None
3222
3125
                raise errors.BzrCommandError(
3223
3126
                    "Could not parse --commit-time: " + str(e))
3224
3127
 
 
3128
        # TODO: Need a blackbox test for invoking the external editor; may be
 
3129
        # slightly problematic to run this cross-platform.
 
3130
 
 
3131
        # TODO: do more checks that the commit will succeed before
 
3132
        # spending the user's valuable time typing a commit message.
 
3133
 
3225
3134
        properties = {}
3226
3135
 
3227
 
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
3136
        tree, selected_list = tree_files(selected_list)
3228
3137
        if selected_list == ['']:
3229
3138
            # workaround - commit of root of tree should be exactly the same
3230
3139
            # as just default commit in that tree, and succeed even though
3265
3174
        def get_message(commit_obj):
3266
3175
            """Callback to get commit message"""
3267
3176
            if file:
3268
 
                f = open(file)
3269
 
                try:
3270
 
                    my_message = f.read().decode(osutils.get_user_encoding())
3271
 
                finally:
3272
 
                    f.close()
 
3177
                my_message = codecs.open(
 
3178
                    file, 'rt', osutils.get_user_encoding()).read()
3273
3179
            elif message is not None:
3274
3180
                my_message = message
3275
3181
            else:
3283
3189
                # make_commit_message_template_encoded returns user encoding.
3284
3190
                # We probably want to be using edit_commit_message instead to
3285
3191
                # avoid this.
3286
 
                my_message = set_commit_message(commit_obj)
3287
 
                if my_message is None:
3288
 
                    start_message = generate_commit_message_template(commit_obj)
3289
 
                    my_message = edit_commit_message_encoded(text,
3290
 
                        start_message=start_message)
 
3192
                start_message = generate_commit_message_template(commit_obj)
 
3193
                my_message = edit_commit_message_encoded(text,
 
3194
                    start_message=start_message)
3291
3195
                if my_message is None:
3292
3196
                    raise errors.BzrCommandError("please specify a commit"
3293
3197
                        " message with either --message or --file")
3306
3210
                        reporter=None, verbose=verbose, revprops=properties,
3307
3211
                        authors=author, timestamp=commit_stamp,
3308
3212
                        timezone=offset,
3309
 
                        exclude=tree.safe_relpath_files(exclude),
3310
 
                        lossy=lossy)
 
3213
                        exclude=safe_relpath_files(tree, exclude))
3311
3214
        except PointlessCommit:
3312
3215
            raise errors.BzrCommandError("No changes to commit."
3313
 
                " Please 'bzr add' the files you want to commit, or use"
3314
 
                " --unchanged to force an empty commit.")
 
3216
                              " Use --unchanged to commit anyhow.")
3315
3217
        except ConflictsInTree:
3316
3218
            raise errors.BzrCommandError('Conflicts detected in working '
3317
3219
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3398
3300
 
3399
3301
 
3400
3302
class cmd_upgrade(Command):
3401
 
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
3402
 
 
3403
 
    When the default format has changed after a major new release of
3404
 
    Bazaar, you may be informed during certain operations that you
3405
 
    should upgrade. Upgrading to a newer format may improve performance
3406
 
    or make new features available. It may however limit interoperability
3407
 
    with older repositories or with older versions of Bazaar.
3408
 
 
3409
 
    If you wish to upgrade to a particular format rather than the
3410
 
    current default, that can be specified using the --format option.
3411
 
    As a consequence, you can use the upgrade command this way to
3412
 
    "downgrade" to an earlier format, though some conversions are
3413
 
    a one way process (e.g. changing from the 1.x default to the
3414
 
    2.x default) so downgrading is not always possible.
3415
 
 
3416
 
    A backup.bzr.~#~ directory is created at the start of the conversion
3417
 
    process (where # is a number). By default, this is left there on
3418
 
    completion. If the conversion fails, delete the new .bzr directory
3419
 
    and rename this one back in its place. Use the --clean option to ask
3420
 
    for the backup.bzr directory to be removed on successful conversion.
3421
 
    Alternatively, you can delete it by hand if everything looks good
3422
 
    afterwards.
3423
 
 
3424
 
    If the location given is a shared repository, dependent branches
3425
 
    are also converted provided the repository converts successfully.
3426
 
    If the conversion of a branch fails, remaining branches are still
3427
 
    tried.
3428
 
 
3429
 
    For more information on upgrades, see the Bazaar Upgrade Guide,
3430
 
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
 
3303
    __doc__ = """Upgrade branch storage to current format.
 
3304
 
 
3305
    The check command or bzr developers may sometimes advise you to run
 
3306
    this command. When the default format has changed you may also be warned
 
3307
    during other operations to upgrade.
3431
3308
    """
3432
3309
 
3433
 
    _see_also = ['check', 'reconcile', 'formats']
 
3310
    _see_also = ['check']
3434
3311
    takes_args = ['url?']
3435
3312
    takes_options = [
3436
 
        RegistryOption('format',
3437
 
            help='Upgrade to a specific format.  See "bzr help'
3438
 
                 ' formats" for details.',
3439
 
            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3440
 
            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3441
 
            value_switches=True, title='Branch format'),
3442
 
        Option('clean',
3443
 
            help='Remove the backup.bzr directory if successful.'),
3444
 
        Option('dry-run',
3445
 
            help="Show what would be done, but don't actually do anything."),
3446
 
    ]
 
3313
                    RegistryOption('format',
 
3314
                        help='Upgrade to a specific format.  See "bzr help'
 
3315
                             ' formats" for details.',
 
3316
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3317
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
 
3318
                        value_switches=True, title='Branch format'),
 
3319
                    ]
3447
3320
 
3448
 
    def run(self, url='.', format=None, clean=False, dry_run=False):
 
3321
    def run(self, url='.', format=None):
3449
3322
        from bzrlib.upgrade import upgrade
3450
 
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3451
 
        if exceptions:
3452
 
            if len(exceptions) == 1:
3453
 
                # Compatibility with historical behavior
3454
 
                raise exceptions[0]
3455
 
            else:
3456
 
                return 3
 
3323
        upgrade(url, format)
3457
3324
 
3458
3325
 
3459
3326
class cmd_whoami(Command):
3468
3335
 
3469
3336
            bzr whoami "Frank Chu <fchu@example.com>"
3470
3337
    """
3471
 
    takes_options = [ 'directory',
3472
 
                      Option('email',
 
3338
    takes_options = [ Option('email',
3473
3339
                             help='Display email address only.'),
3474
3340
                      Option('branch',
3475
3341
                             help='Set identity for the current branch instead of '
3479
3345
    encoding_type = 'replace'
3480
3346
 
3481
3347
    @display_command
3482
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
3348
    def run(self, email=False, branch=False, name=None):
3483
3349
        if name is None:
3484
 
            if directory is None:
3485
 
                # use branch if we're inside one; otherwise global config
3486
 
                try:
3487
 
                    c = Branch.open_containing(u'.')[0].get_config()
3488
 
                except errors.NotBranchError:
3489
 
                    c = _mod_config.GlobalConfig()
3490
 
            else:
3491
 
                c = Branch.open(directory).get_config()
 
3350
            # use branch if we're inside one; otherwise global config
 
3351
            try:
 
3352
                c = Branch.open_containing('.')[0].get_config()
 
3353
            except errors.NotBranchError:
 
3354
                c = config.GlobalConfig()
3492
3355
            if email:
3493
3356
                self.outf.write(c.user_email() + '\n')
3494
3357
            else:
3495
3358
                self.outf.write(c.username() + '\n')
3496
3359
            return
3497
3360
 
3498
 
        if email:
3499
 
            raise errors.BzrCommandError("--email can only be used to display existing "
3500
 
                                         "identity")
3501
 
 
3502
3361
        # display a warning if an email address isn't included in the given name.
3503
3362
        try:
3504
 
            _mod_config.extract_email_address(name)
 
3363
            config.extract_email_address(name)
3505
3364
        except errors.NoEmailInUsername, e:
3506
3365
            warning('"%s" does not seem to contain an email address.  '
3507
3366
                    'This is allowed, but not recommended.', name)
3508
3367
 
3509
3368
        # use global config unless --branch given
3510
3369
        if branch:
3511
 
            if directory is None:
3512
 
                c = Branch.open_containing(u'.')[0].get_config()
3513
 
            else:
3514
 
                c = Branch.open(directory).get_config()
 
3370
            c = Branch.open_containing('.')[0].get_config()
3515
3371
        else:
3516
 
            c = _mod_config.GlobalConfig()
 
3372
            c = config.GlobalConfig()
3517
3373
        c.set_user_option('email', name)
3518
3374
 
3519
3375
 
3529
3385
 
3530
3386
    _see_also = ['info']
3531
3387
    takes_args = ['nickname?']
3532
 
    takes_options = ['directory']
3533
 
    def run(self, nickname=None, directory=u'.'):
3534
 
        branch = Branch.open_containing(directory)[0]
 
3388
    def run(self, nickname=None):
 
3389
        branch = Branch.open_containing(u'.')[0]
3535
3390
        if nickname is None:
3536
3391
            self.printme(branch)
3537
3392
        else:
3586
3441
                'bzr alias --remove expects an alias to remove.')
3587
3442
        # If alias is not found, print something like:
3588
3443
        # unalias: foo: not found
3589
 
        c = _mod_config.GlobalConfig()
 
3444
        c = config.GlobalConfig()
3590
3445
        c.unset_alias(alias_name)
3591
3446
 
3592
3447
    @display_command
3593
3448
    def print_aliases(self):
3594
3449
        """Print out the defined aliases in a similar format to bash."""
3595
 
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3450
        aliases = config.GlobalConfig().get_aliases()
3596
3451
        for key, value in sorted(aliases.iteritems()):
3597
3452
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3598
3453
 
3608
3463
 
3609
3464
    def set_alias(self, alias_name, alias_command):
3610
3465
        """Save the alias in the global config."""
3611
 
        c = _mod_config.GlobalConfig()
 
3466
        c = config.GlobalConfig()
3612
3467
        c.set_alias(alias_name, alias_command)
3613
3468
 
3614
3469
 
3649
3504
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3650
3505
    into a pdb postmortem session.
3651
3506
 
3652
 
    The --coverage=DIRNAME global option produces a report with covered code
3653
 
    indicated.
3654
 
 
3655
3507
    :Examples:
3656
3508
        Run only tests relating to 'ignore'::
3657
3509
 
3668
3520
        if typestring == "sftp":
3669
3521
            from bzrlib.tests import stub_sftp
3670
3522
            return stub_sftp.SFTPAbsoluteServer
3671
 
        elif typestring == "memory":
 
3523
        if typestring == "memory":
3672
3524
            from bzrlib.tests import test_server
3673
3525
            return memory.MemoryServer
3674
 
        elif typestring == "fakenfs":
 
3526
        if typestring == "fakenfs":
3675
3527
            from bzrlib.tests import test_server
3676
3528
            return test_server.FakeNFSServer
3677
3529
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3690
3542
                                 'throughout the test suite.',
3691
3543
                            type=get_transport_type),
3692
3544
                     Option('benchmark',
3693
 
                            help='Run the benchmarks rather than selftests.',
3694
 
                            hidden=True),
 
3545
                            help='Run the benchmarks rather than selftests.'),
3695
3546
                     Option('lsprof-timed',
3696
3547
                            help='Generate lsprof output for benchmarked'
3697
3548
                                 ' sections of code.'),
3698
3549
                     Option('lsprof-tests',
3699
3550
                            help='Generate lsprof output for each test.'),
 
3551
                     Option('cache-dir', type=str,
 
3552
                            help='Cache intermediate benchmark output in this '
 
3553
                                 'directory.'),
3700
3554
                     Option('first',
3701
3555
                            help='Run all tests, but run specified tests first.',
3702
3556
                            short_name='f',
3711
3565
                     Option('randomize', type=str, argname="SEED",
3712
3566
                            help='Randomize the order of tests using the given'
3713
3567
                                 ' seed or "now" for the current time.'),
3714
 
                     ListOption('exclude', type=str, argname="PATTERN",
3715
 
                                short_name='x',
3716
 
                                help='Exclude tests that match this regular'
3717
 
                                ' expression.'),
 
3568
                     Option('exclude', type=str, argname="PATTERN",
 
3569
                            short_name='x',
 
3570
                            help='Exclude tests that match this regular'
 
3571
                                 ' expression.'),
3718
3572
                     Option('subunit',
3719
3573
                        help='Output test progress via subunit.'),
3720
3574
                     Option('strict', help='Fail on missing dependencies or '
3736
3590
 
3737
3591
    def run(self, testspecs_list=None, verbose=False, one=False,
3738
3592
            transport=None, benchmark=None,
3739
 
            lsprof_timed=None,
 
3593
            lsprof_timed=None, cache_dir=None,
3740
3594
            first=False, list_only=False,
3741
3595
            randomize=None, exclude=None, strict=False,
3742
3596
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3743
3597
            parallel=None, lsprof_tests=False):
3744
 
        from bzrlib import tests
3745
 
 
 
3598
        from bzrlib.tests import selftest
 
3599
        import bzrlib.benchmarks as benchmarks
 
3600
        from bzrlib.benchmarks import tree_creator
 
3601
 
 
3602
        # Make deprecation warnings visible, unless -Werror is set
 
3603
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3604
 
 
3605
        if cache_dir is not None:
 
3606
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3746
3607
        if testspecs_list is not None:
3747
3608
            pattern = '|'.join(testspecs_list)
3748
3609
        else:
3756
3617
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3757
3618
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3758
3619
            # stdout, which would corrupt the subunit stream. 
3759
 
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3760
 
            # following code can be deleted when it's sufficiently deployed
3761
 
            # -- vila/mgz 20100514
3762
 
            if (sys.platform == "win32"
3763
 
                and getattr(sys.stdout, 'fileno', None) is not None):
 
3620
            if sys.platform == "win32" and sys.stdout.fileno() >= 0:
3764
3621
                import msvcrt
3765
3622
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3766
3623
        if parallel:
3767
3624
            self.additional_selftest_args.setdefault(
3768
3625
                'suite_decorators', []).append(parallel)
3769
3626
        if benchmark:
3770
 
            raise errors.BzrCommandError(
3771
 
                "--benchmark is no longer supported from bzr 2.2; "
3772
 
                "use bzr-usertest instead")
3773
 
        test_suite_factory = None
3774
 
        if not exclude:
3775
 
            exclude_pattern = None
 
3627
            test_suite_factory = benchmarks.test_suite
 
3628
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3629
            verbose = not is_quiet()
 
3630
            # TODO: should possibly lock the history file...
 
3631
            benchfile = open(".perf_history", "at", buffering=1)
 
3632
            self.add_cleanup(benchfile.close)
3776
3633
        else:
3777
 
            exclude_pattern = '(' + '|'.join(exclude) + ')'
 
3634
            test_suite_factory = None
 
3635
            benchfile = None
3778
3636
        selftest_kwargs = {"verbose": verbose,
3779
3637
                          "pattern": pattern,
3780
3638
                          "stop_on_failure": one,
3782
3640
                          "test_suite_factory": test_suite_factory,
3783
3641
                          "lsprof_timed": lsprof_timed,
3784
3642
                          "lsprof_tests": lsprof_tests,
 
3643
                          "bench_history": benchfile,
3785
3644
                          "matching_tests_first": first,
3786
3645
                          "list_only": list_only,
3787
3646
                          "random_seed": randomize,
3788
 
                          "exclude_pattern": exclude_pattern,
 
3647
                          "exclude_pattern": exclude,
3789
3648
                          "strict": strict,
3790
3649
                          "load_list": load_list,
3791
3650
                          "debug_flags": debugflag,
3792
3651
                          "starting_with": starting_with
3793
3652
                          }
3794
3653
        selftest_kwargs.update(self.additional_selftest_args)
3795
 
 
3796
 
        # Make deprecation warnings visible, unless -Werror is set
3797
 
        cleanup = symbol_versioning.activate_deprecation_warnings(
3798
 
            override=False)
3799
 
        try:
3800
 
            result = tests.selftest(**selftest_kwargs)
3801
 
        finally:
3802
 
            cleanup()
 
3654
        result = selftest(**selftest_kwargs)
3803
3655
        return int(not result)
3804
3656
 
3805
3657
 
3843
3695
 
3844
3696
        branch1 = Branch.open_containing(branch)[0]
3845
3697
        branch2 = Branch.open_containing(other)[0]
3846
 
        self.add_cleanup(branch1.lock_read().unlock)
3847
 
        self.add_cleanup(branch2.lock_read().unlock)
 
3698
        branch1.lock_read()
 
3699
        self.add_cleanup(branch1.unlock)
 
3700
        branch2.lock_read()
 
3701
        self.add_cleanup(branch2.unlock)
3848
3702
        last1 = ensure_null(branch1.last_revision())
3849
3703
        last2 = ensure_null(branch2.last_revision())
3850
3704
 
3860
3714
    The source of the merge can be specified either in the form of a branch,
3861
3715
    or in the form of a path to a file containing a merge directive generated
3862
3716
    with bzr send. If neither is specified, the default is the upstream branch
3863
 
    or the branch most recently merged using --remember.  The source of the
3864
 
    merge may also be specified in the form of a path to a file in another
3865
 
    branch:  in this case, only the modifications to that file are merged into
3866
 
    the current working tree.
3867
 
 
3868
 
    When merging from a branch, by default bzr will try to merge in all new
3869
 
    work from the other branch, automatically determining an appropriate base
3870
 
    revision.  If this fails, you may need to give an explicit base.
3871
 
 
3872
 
    To pick a different ending revision, pass "--revision OTHER".  bzr will
3873
 
    try to merge in all new work up to and including revision OTHER.
3874
 
 
3875
 
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
3876
 
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
3877
 
    causes some revisions to be skipped, i.e. if the destination branch does
3878
 
    not already contain revision BASE, such a merge is commonly referred to as
3879
 
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
3880
 
    cherrypicks. The changes look like a normal commit, and the history of the
3881
 
    changes from the other branch is not stored in the commit.
3882
 
 
3883
 
    Revision numbers are always relative to the source branch.
 
3717
    or the branch most recently merged using --remember.
 
3718
 
 
3719
    When merging a branch, by default the tip will be merged. To pick a different
 
3720
    revision, pass --revision. If you specify two values, the first will be used as
 
3721
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
3722
    available revisions, like this is commonly referred to as "cherrypicking".
 
3723
 
 
3724
    Revision numbers are always relative to the branch being merged.
 
3725
 
 
3726
    By default, bzr will try to merge in all new work from the other
 
3727
    branch, automatically determining an appropriate base.  If this
 
3728
    fails, you may need to give an explicit base.
3884
3729
 
3885
3730
    Merge will do its best to combine the changes in two branches, but there
3886
3731
    are some kinds of problems only a human can fix.  When it encounters those,
3889
3734
 
3890
3735
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
3891
3736
 
3892
 
    If there is no default branch set, the first merge will set it (use
3893
 
    --no-remember to avoid settting it). After that, you can omit the branch
3894
 
    to use the default.  To change the default, use --remember. The value will
3895
 
    only be saved if the remote location can be accessed.
 
3737
    If there is no default branch set, the first merge will set it. After
 
3738
    that, you can omit the branch to use the default.  To change the
 
3739
    default, use --remember. The value will only be saved if the remote
 
3740
    location can be accessed.
3896
3741
 
3897
3742
    The results of the merge are placed into the destination working
3898
3743
    directory, where they can be reviewed (with bzr diff), tested, and then
3899
3744
    committed to record the result of the merge.
3900
3745
 
3901
3746
    merge refuses to run if there are any uncommitted changes, unless
3902
 
    --force is given.  If --force is given, then the changes from the source 
3903
 
    will be merged with the current working tree, including any uncommitted
3904
 
    changes in the tree.  The --force option can also be used to create a
 
3747
    --force is given. The --force option can also be used to create a
3905
3748
    merge revision which has more than two parents.
3906
3749
 
3907
3750
    If one would like to merge changes from the working tree of the other
3912
3755
    you to apply each diff hunk and file change, similar to "shelve".
3913
3756
 
3914
3757
    :Examples:
3915
 
        To merge all new revisions from bzr.dev::
 
3758
        To merge the latest revision from bzr.dev::
3916
3759
 
3917
3760
            bzr merge ../bzr.dev
3918
3761
 
3955
3798
                ' completely merged into the source, pull from the'
3956
3799
                ' source rather than merging.  When this happens,'
3957
3800
                ' you do not need to commit the result.'),
3958
 
        custom_help('directory',
 
3801
        Option('directory',
3959
3802
               help='Branch to merge into, '
3960
 
                    'rather than the one containing the working directory.'),
 
3803
                    'rather than the one containing the working directory.',
 
3804
               short_name='d',
 
3805
               type=unicode,
 
3806
               ),
3961
3807
        Option('preview', help='Instead of merging, show a diff of the'
3962
3808
               ' merge.'),
3963
3809
        Option('interactive', help='Select changes interactively.',
3965
3811
    ]
3966
3812
 
3967
3813
    def run(self, location=None, revision=None, force=False,
3968
 
            merge_type=None, show_base=False, reprocess=None, remember=None,
 
3814
            merge_type=None, show_base=False, reprocess=None, remember=False,
3969
3815
            uncommitted=False, pull=False,
3970
3816
            directory=None,
3971
3817
            preview=False,
3979
3825
        merger = None
3980
3826
        allow_pending = True
3981
3827
        verified = 'inapplicable'
3982
 
 
3983
3828
        tree = WorkingTree.open_containing(directory)[0]
3984
 
        if tree.branch.revno() == 0:
3985
 
            raise errors.BzrCommandError('Merging into empty branches not currently supported, '
3986
 
                                         'https://bugs.launchpad.net/bzr/+bug/308562')
3987
3829
 
3988
3830
        try:
3989
3831
            basis_tree = tree.revision_tree(tree.last_revision())
4000
3842
            unversioned_filter=tree.is_ignored, view_info=view_info)
4001
3843
        pb = ui.ui_factory.nested_progress_bar()
4002
3844
        self.add_cleanup(pb.finished)
4003
 
        self.add_cleanup(tree.lock_write().unlock)
 
3845
        tree.lock_write()
 
3846
        self.add_cleanup(tree.unlock)
4004
3847
        if location is not None:
4005
3848
            try:
4006
3849
                mergeable = bundle.read_mergeable_from_url(location,
4035
3878
        self.sanity_check_merger(merger)
4036
3879
        if (merger.base_rev_id == merger.other_rev_id and
4037
3880
            merger.other_rev_id is not None):
4038
 
            # check if location is a nonexistent file (and not a branch) to
4039
 
            # disambiguate the 'Nothing to do'
4040
 
            if merger.interesting_files:
4041
 
                if not merger.other_tree.has_filename(
4042
 
                    merger.interesting_files[0]):
4043
 
                    note("merger: " + str(merger))
4044
 
                    raise errors.PathsDoNotExist([location])
4045
3881
            note('Nothing to do.')
4046
3882
            return 0
4047
 
        if pull and not preview:
 
3883
        if pull:
4048
3884
            if merger.interesting_files is not None:
4049
3885
                raise errors.BzrCommandError('Cannot pull individual files')
4050
3886
            if (merger.base_rev_id == tree.last_revision()):
4074
3910
    def _do_preview(self, merger):
4075
3911
        from bzrlib.diff import show_diff_trees
4076
3912
        result_tree = self._get_preview(merger)
4077
 
        path_encoding = osutils.get_diff_header_encoding()
4078
3913
        show_diff_trees(merger.this_tree, result_tree, self.outf,
4079
 
                        old_label='', new_label='',
4080
 
                        path_encoding=path_encoding)
 
3914
                        old_label='', new_label='')
4081
3915
 
4082
3916
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
4083
3917
        merger.change_reporter = change_reporter
4159
3993
        if other_revision_id is None:
4160
3994
            other_revision_id = _mod_revision.ensure_null(
4161
3995
                other_branch.last_revision())
4162
 
        # Remember where we merge from. We need to remember if:
4163
 
        # - user specify a location (and we don't merge from the parent
4164
 
        #   branch)
4165
 
        # - user ask to remember or there is no previous location set to merge
4166
 
        #   from and user didn't ask to *not* remember
4167
 
        if (user_location is not None
4168
 
            and ((remember
4169
 
                  or (remember is None
4170
 
                      and tree.branch.get_submit_branch() is None)))):
 
3996
        # Remember where we merge from
 
3997
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3998
             user_location is not None):
4171
3999
            tree.branch.set_submit_branch(other_branch.base)
4172
 
        # Merge tags (but don't set them in the master branch yet, the user
4173
 
        # might revert this merge).  Commit will propagate them.
4174
 
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
 
4000
        _merge_tags_if_possible(other_branch, tree.branch)
4175
4001
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4176
4002
            other_revision_id, base_revision_id, other_branch, base_branch)
4177
4003
        if other_path != '':
4278
4104
        from bzrlib.conflicts import restore
4279
4105
        if merge_type is None:
4280
4106
            merge_type = _mod_merge.Merge3Merger
4281
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4282
 
        self.add_cleanup(tree.lock_write().unlock)
 
4107
        tree, file_list = tree_files(file_list)
 
4108
        tree.lock_write()
 
4109
        self.add_cleanup(tree.unlock)
4283
4110
        parents = tree.get_parent_ids()
4284
4111
        if len(parents) != 2:
4285
4112
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4345
4172
    last committed revision is used.
4346
4173
 
4347
4174
    To remove only some changes, without reverting to a prior version, use
4348
 
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
4349
 
    will remove the changes introduced by the second last commit (-2), without
4350
 
    affecting the changes introduced by the last commit (-1).  To remove
4351
 
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
4175
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
4176
    changes introduced by -2, without affecting the changes introduced by -1.
 
4177
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4352
4178
 
4353
4179
    By default, any files that have been manually changed will be backed up
4354
4180
    first.  (Files changed only by merge are not backed up.)  Backup files have
4384
4210
    target branches.
4385
4211
    """
4386
4212
 
4387
 
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4213
    _see_also = ['cat', 'export']
4388
4214
    takes_options = [
4389
4215
        'revision',
4390
4216
        Option('no-backup', "Do not save backups of reverted files."),
4395
4221
 
4396
4222
    def run(self, revision=None, no_backup=False, file_list=None,
4397
4223
            forget_merges=None):
4398
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4399
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
4224
        tree, file_list = tree_files(file_list)
 
4225
        tree.lock_tree_write()
 
4226
        self.add_cleanup(tree.unlock)
4400
4227
        if forget_merges:
4401
4228
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4402
4229
        else:
4491
4318
    _see_also = ['merge', 'pull']
4492
4319
    takes_args = ['other_branch?']
4493
4320
    takes_options = [
4494
 
        'directory',
4495
4321
        Option('reverse', 'Reverse the order of revisions.'),
4496
4322
        Option('mine-only',
4497
4323
               'Display changes in the local branch only.'),
4519
4345
            theirs_only=False,
4520
4346
            log_format=None, long=False, short=False, line=False,
4521
4347
            show_ids=False, verbose=False, this=False, other=False,
4522
 
            include_merges=False, revision=None, my_revision=None,
4523
 
            directory=u'.'):
 
4348
            include_merges=False, revision=None, my_revision=None):
4524
4349
        from bzrlib.missing import find_unmerged, iter_log_revisions
4525
4350
        def message(s):
4526
4351
            if not is_quiet():
4539
4364
        elif theirs_only:
4540
4365
            restrict = 'remote'
4541
4366
 
4542
 
        local_branch = Branch.open_containing(directory)[0]
4543
 
        self.add_cleanup(local_branch.lock_read().unlock)
 
4367
        local_branch = Branch.open_containing(u".")[0]
 
4368
        local_branch.lock_read()
 
4369
        self.add_cleanup(local_branch.unlock)
4544
4370
 
4545
4371
        parent = local_branch.get_parent()
4546
4372
        if other_branch is None:
4557
4383
        if remote_branch.base == local_branch.base:
4558
4384
            remote_branch = local_branch
4559
4385
        else:
4560
 
            self.add_cleanup(remote_branch.lock_read().unlock)
 
4386
            remote_branch.lock_read()
 
4387
            self.add_cleanup(remote_branch.unlock)
4561
4388
 
4562
4389
        local_revid_range = _revision_range_to_revid_range(
4563
4390
            _get_revision_range(my_revision, local_branch,
4618
4445
            message("Branches are up to date.\n")
4619
4446
        self.cleanup_now()
4620
4447
        if not status_code and parent is None and other_branch is not None:
4621
 
            self.add_cleanup(local_branch.lock_write().unlock)
 
4448
            local_branch.lock_write()
 
4449
            self.add_cleanup(local_branch.unlock)
4622
4450
            # handle race conditions - a parent might be set while we run.
4623
4451
            if local_branch.get_parent() is None:
4624
4452
                local_branch.set_parent(remote_branch.base)
4683
4511
 
4684
4512
    @display_command
4685
4513
    def run(self, verbose=False):
4686
 
        from bzrlib import plugin
4687
 
        # Don't give writelines a generator as some codecs don't like that
4688
 
        self.outf.writelines(
4689
 
            list(plugin.describe_plugins(show_paths=verbose)))
 
4514
        import bzrlib.plugin
 
4515
        from inspect import getdoc
 
4516
        result = []
 
4517
        for name, plugin in bzrlib.plugin.plugins().items():
 
4518
            version = plugin.__version__
 
4519
            if version == 'unknown':
 
4520
                version = ''
 
4521
            name_ver = '%s %s' % (name, version)
 
4522
            d = getdoc(plugin.module)
 
4523
            if d:
 
4524
                doc = d.split('\n')[0]
 
4525
            else:
 
4526
                doc = '(no description)'
 
4527
            result.append((name_ver, doc, plugin.path()))
 
4528
        for name_ver, doc, path in sorted(result):
 
4529
            self.outf.write("%s\n" % name_ver)
 
4530
            self.outf.write("   %s\n" % doc)
 
4531
            if verbose:
 
4532
                self.outf.write("   %s\n" % path)
 
4533
            self.outf.write("\n")
4690
4534
 
4691
4535
 
4692
4536
class cmd_testament(Command):
4708
4552
            b = Branch.open_containing(branch)[0]
4709
4553
        else:
4710
4554
            b = Branch.open(branch)
4711
 
        self.add_cleanup(b.lock_read().unlock)
 
4555
        b.lock_read()
 
4556
        self.add_cleanup(b.unlock)
4712
4557
        if revision is None:
4713
4558
            rev_id = b.last_revision()
4714
4559
        else:
4738
4583
                     Option('long', help='Show commit date in annotations.'),
4739
4584
                     'revision',
4740
4585
                     'show-ids',
4741
 
                     'directory',
4742
4586
                     ]
4743
4587
    encoding_type = 'exact'
4744
4588
 
4745
4589
    @display_command
4746
4590
    def run(self, filename, all=False, long=False, revision=None,
4747
 
            show_ids=False, directory=None):
4748
 
        from bzrlib.annotate import (
4749
 
            annotate_file_tree,
4750
 
            )
 
4591
            show_ids=False):
 
4592
        from bzrlib.annotate import annotate_file, annotate_file_tree
4751
4593
        wt, branch, relpath = \
4752
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4594
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
4753
4595
        if wt is not None:
4754
 
            self.add_cleanup(wt.lock_read().unlock)
 
4596
            wt.lock_read()
 
4597
            self.add_cleanup(wt.unlock)
4755
4598
        else:
4756
 
            self.add_cleanup(branch.lock_read().unlock)
 
4599
            branch.lock_read()
 
4600
            self.add_cleanup(branch.unlock)
4757
4601
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4758
 
        self.add_cleanup(tree.lock_read().unlock)
4759
 
        if wt is not None and revision is None:
 
4602
        tree.lock_read()
 
4603
        self.add_cleanup(tree.unlock)
 
4604
        if wt is not None:
4760
4605
            file_id = wt.path2id(relpath)
4761
4606
        else:
4762
4607
            file_id = tree.path2id(relpath)
4763
4608
        if file_id is None:
4764
4609
            raise errors.NotVersionedError(filename)
 
4610
        file_version = tree.inventory[file_id].revision
4765
4611
        if wt is not None and revision is None:
4766
4612
            # If there is a tree and we're not annotating historical
4767
4613
            # versions, annotate the working tree's content.
4768
4614
            annotate_file_tree(wt, file_id, self.outf, long, all,
4769
4615
                show_ids=show_ids)
4770
4616
        else:
4771
 
            annotate_file_tree(tree, file_id, self.outf, long, all,
4772
 
                show_ids=show_ids, branch=branch)
 
4617
            annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4618
                          show_ids=show_ids)
4773
4619
 
4774
4620
 
4775
4621
class cmd_re_sign(Command):
4778
4624
 
4779
4625
    hidden = True # is this right ?
4780
4626
    takes_args = ['revision_id*']
4781
 
    takes_options = ['directory', 'revision']
 
4627
    takes_options = ['revision']
4782
4628
 
4783
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
4629
    def run(self, revision_id_list=None, revision=None):
4784
4630
        if revision_id_list is not None and revision is not None:
4785
4631
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4786
4632
        if revision_id_list is None and revision is None:
4787
4633
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4788
 
        b = WorkingTree.open_containing(directory)[0].branch
4789
 
        self.add_cleanup(b.lock_write().unlock)
 
4634
        b = WorkingTree.open_containing(u'.')[0].branch
 
4635
        b.lock_write()
 
4636
        self.add_cleanup(b.unlock)
4790
4637
        return self._run(b, revision_id_list, revision)
4791
4638
 
4792
4639
    def _run(self, b, revision_id_list, revision):
4839
4686
 
4840
4687
class cmd_bind(Command):
4841
4688
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
4842
 
    If no branch is supplied, rebind to the last bound location.
4843
4689
 
4844
4690
    Once converted into a checkout, commits must succeed on the master branch
4845
4691
    before they will be applied to the local branch.
4851
4697
 
4852
4698
    _see_also = ['checkouts', 'unbind']
4853
4699
    takes_args = ['location?']
4854
 
    takes_options = ['directory']
 
4700
    takes_options = []
4855
4701
 
4856
 
    def run(self, location=None, directory=u'.'):
4857
 
        b, relpath = Branch.open_containing(directory)
 
4702
    def run(self, location=None):
 
4703
        b, relpath = Branch.open_containing(u'.')
4858
4704
        if location is None:
4859
4705
            try:
4860
4706
                location = b.get_old_bound_location()
4887
4733
 
4888
4734
    _see_also = ['checkouts', 'bind']
4889
4735
    takes_args = []
4890
 
    takes_options = ['directory']
 
4736
    takes_options = []
4891
4737
 
4892
 
    def run(self, directory=u'.'):
4893
 
        b, relpath = Branch.open_containing(directory)
 
4738
    def run(self):
 
4739
        b, relpath = Branch.open_containing(u'.')
4894
4740
        if not b.unbind():
4895
4741
            raise errors.BzrCommandError('Local branch is not bound')
4896
4742
 
4942
4788
            b = control.open_branch()
4943
4789
 
4944
4790
        if tree is not None:
4945
 
            self.add_cleanup(tree.lock_write().unlock)
 
4791
            tree.lock_write()
 
4792
            self.add_cleanup(tree.unlock)
4946
4793
        else:
4947
 
            self.add_cleanup(b.lock_write().unlock)
 
4794
            b.lock_write()
 
4795
            self.add_cleanup(b.unlock)
4948
4796
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4949
4797
 
4950
4798
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4989
4837
            self.outf.write('The above revision(s) will be removed.\n')
4990
4838
 
4991
4839
        if not force:
4992
 
            if not ui.ui_factory.confirm_action(
4993
 
                    u'Uncommit these revisions',
4994
 
                    'bzrlib.builtins.uncommit',
4995
 
                    {}):
4996
 
                self.outf.write('Canceled\n')
 
4840
            if not ui.ui_factory.get_boolean('Are you sure'):
 
4841
                self.outf.write('Canceled')
4997
4842
                return 0
4998
4843
 
4999
4844
        mutter('Uncommitting from {%s} to {%s}',
5005
4850
 
5006
4851
 
5007
4852
class cmd_break_lock(Command):
5008
 
    __doc__ = """Break a dead lock.
5009
 
 
5010
 
    This command breaks a lock on a repository, branch, working directory or
5011
 
    config file.
 
4853
    __doc__ = """Break a dead lock on a repository, branch or working directory.
5012
4854
 
5013
4855
    CAUTION: Locks should only be broken when you are sure that the process
5014
4856
    holding the lock has been stopped.
5019
4861
    :Examples:
5020
4862
        bzr break-lock
5021
4863
        bzr break-lock bzr+ssh://example.com/bzr/foo
5022
 
        bzr break-lock --conf ~/.bazaar
5023
4864
    """
5024
 
 
5025
4865
    takes_args = ['location?']
5026
 
    takes_options = [
5027
 
        Option('config',
5028
 
               help='LOCATION is the directory where the config lock is.'),
5029
 
        Option('force',
5030
 
            help='Do not ask for confirmation before breaking the lock.'),
5031
 
        ]
5032
4866
 
5033
 
    def run(self, location=None, config=False, force=False):
 
4867
    def run(self, location=None, show=False):
5034
4868
        if location is None:
5035
4869
            location = u'.'
5036
 
        if force:
5037
 
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5038
 
                None,
5039
 
                {'bzrlib.lockdir.break': True})
5040
 
        if config:
5041
 
            conf = _mod_config.LockableConfig(file_name=location)
5042
 
            conf.break_lock()
5043
 
        else:
5044
 
            control, relpath = bzrdir.BzrDir.open_containing(location)
5045
 
            try:
5046
 
                control.break_lock()
5047
 
            except NotImplementedError:
5048
 
                pass
 
4870
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4871
        try:
 
4872
            control.break_lock()
 
4873
        except NotImplementedError:
 
4874
            pass
5049
4875
 
5050
4876
 
5051
4877
class cmd_wait_until_signalled(Command):
5080
4906
                    'result in a dynamically allocated port.  The default port '
5081
4907
                    'depends on the protocol.',
5082
4908
               type=str),
5083
 
        custom_help('directory',
5084
 
               help='Serve contents of this directory.'),
 
4909
        Option('directory',
 
4910
               help='Serve contents of this directory.',
 
4911
               type=unicode),
5085
4912
        Option('allow-writes',
5086
4913
               help='By default the server is a readonly server.  Supplying '
5087
4914
                    '--allow-writes enables write access to the contents of '
5114
4941
 
5115
4942
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
5116
4943
            protocol=None):
5117
 
        from bzrlib import transport
 
4944
        from bzrlib.transport import get_transport, transport_server_registry
5118
4945
        if directory is None:
5119
4946
            directory = os.getcwd()
5120
4947
        if protocol is None:
5121
 
            protocol = transport.transport_server_registry.get()
 
4948
            protocol = transport_server_registry.get()
5122
4949
        host, port = self.get_host_and_port(port)
5123
4950
        url = urlutils.local_path_to_url(directory)
5124
4951
        if not allow_writes:
5125
4952
            url = 'readonly+' + url
5126
 
        t = transport.get_transport(url)
5127
 
        protocol(t, host, port, inet)
 
4953
        transport = get_transport(url)
 
4954
        protocol(transport, host, port, inet)
5128
4955
 
5129
4956
 
5130
4957
class cmd_join(Command):
5136
4963
    not part of it.  (Such trees can be produced by "bzr split", but also by
5137
4964
    running "bzr branch" with the target inside a tree.)
5138
4965
 
5139
 
    The result is a combined tree, with the subtree no longer an independent
 
4966
    The result is a combined tree, with the subtree no longer an independant
5140
4967
    part.  This is marked as a merge of the subtree into the containing tree,
5141
4968
    and all history is preserved.
5142
4969
    """
5223
5050
    _see_also = ['send']
5224
5051
 
5225
5052
    takes_options = [
5226
 
        'directory',
5227
5053
        RegistryOption.from_kwargs('patch-type',
5228
5054
            'The type of patch to include in the directive.',
5229
5055
            title='Patch type',
5242
5068
    encoding_type = 'exact'
5243
5069
 
5244
5070
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5245
 
            sign=False, revision=None, mail_to=None, message=None,
5246
 
            directory=u'.'):
 
5071
            sign=False, revision=None, mail_to=None, message=None):
5247
5072
        from bzrlib.revision import ensure_null, NULL_REVISION
5248
5073
        include_patch, include_bundle = {
5249
5074
            'plain': (False, False),
5250
5075
            'diff': (True, False),
5251
5076
            'bundle': (True, True),
5252
5077
            }[patch_type]
5253
 
        branch = Branch.open(directory)
 
5078
        branch = Branch.open('.')
5254
5079
        stored_submit_branch = branch.get_submit_branch()
5255
5080
        if submit_branch is None:
5256
5081
            submit_branch = stored_submit_branch
5332
5157
    source branch defaults to that containing the working directory, but can
5333
5158
    be changed using --from.
5334
5159
 
5335
 
    Both the submit branch and the public branch follow the usual behavior with
5336
 
    respect to --remember: If there is no default location set, the first send
5337
 
    will set it (use --no-remember to avoid settting it). After that, you can
5338
 
    omit the location to use the default.  To change the default, use
5339
 
    --remember. The value will only be saved if the location can be accessed.
5340
 
 
5341
5160
    In order to calculate those changes, bzr must analyse the submit branch.
5342
5161
    Therefore it is most efficient for the submit branch to be a local mirror.
5343
5162
    If a public location is known for the submit_branch, that location is used
5347
5166
    given, in which case it is sent to a file.
5348
5167
 
5349
5168
    Mail is sent using your preferred mail program.  This should be transparent
5350
 
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
5169
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
5351
5170
    If the preferred client can't be found (or used), your editor will be used.
5352
5171
 
5353
5172
    To use a specific mail program, set the mail_client configuration option.
5412
5231
        ]
5413
5232
 
5414
5233
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5415
 
            no_patch=False, revision=None, remember=None, output=None,
 
5234
            no_patch=False, revision=None, remember=False, output=None,
5416
5235
            format=None, mail_to=None, message=None, body=None,
5417
5236
            strict=None, **kwargs):
5418
5237
        from bzrlib.send import send
5524
5343
        Option('delete',
5525
5344
            help='Delete this tag rather than placing it.',
5526
5345
            ),
5527
 
        custom_help('directory',
5528
 
            help='Branch in which to place the tag.'),
 
5346
        Option('directory',
 
5347
            help='Branch in which to place the tag.',
 
5348
            short_name='d',
 
5349
            type=unicode,
 
5350
            ),
5529
5351
        Option('force',
5530
5352
            help='Replace existing tags.',
5531
5353
            ),
5539
5361
            revision=None,
5540
5362
            ):
5541
5363
        branch, relpath = Branch.open_containing(directory)
5542
 
        self.add_cleanup(branch.lock_write().unlock)
 
5364
        branch.lock_write()
 
5365
        self.add_cleanup(branch.unlock)
5543
5366
        if delete:
5544
5367
            if tag_name is None:
5545
5368
                raise errors.BzrCommandError("No tag specified to delete.")
5546
5369
            branch.tags.delete_tag(tag_name)
5547
 
            note('Deleted tag %s.' % tag_name)
 
5370
            self.outf.write('Deleted tag %s.\n' % tag_name)
5548
5371
        else:
5549
5372
            if revision:
5550
5373
                if len(revision) != 1:
5562
5385
            if (not force) and branch.tags.has_tag(tag_name):
5563
5386
                raise errors.TagAlreadyExists(tag_name)
5564
5387
            branch.tags.set_tag(tag_name, revision_id)
5565
 
            note('Created tag %s.' % tag_name)
 
5388
            self.outf.write('Created tag %s.\n' % tag_name)
5566
5389
 
5567
5390
 
5568
5391
class cmd_tags(Command):
5573
5396
 
5574
5397
    _see_also = ['tag']
5575
5398
    takes_options = [
5576
 
        custom_help('directory',
5577
 
            help='Branch whose tags should be displayed.'),
5578
 
        RegistryOption('sort',
 
5399
        Option('directory',
 
5400
            help='Branch whose tags should be displayed.',
 
5401
            short_name='d',
 
5402
            type=unicode,
 
5403
            ),
 
5404
        RegistryOption.from_kwargs('sort',
5579
5405
            'Sort tags by different criteria.', title='Sorting',
5580
 
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
 
5406
            alpha='Sort tags lexicographically (default).',
 
5407
            time='Sort tags chronologically.',
5581
5408
            ),
5582
5409
        'show-ids',
5583
5410
        'revision',
5584
5411
    ]
5585
5412
 
5586
5413
    @display_command
5587
 
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
5588
 
        from bzrlib.tag import tag_sort_methods
 
5414
    def run(self,
 
5415
            directory='.',
 
5416
            sort='alpha',
 
5417
            show_ids=False,
 
5418
            revision=None,
 
5419
            ):
5589
5420
        branch, relpath = Branch.open_containing(directory)
5590
5421
 
5591
5422
        tags = branch.tags.get_tag_dict().items()
5592
5423
        if not tags:
5593
5424
            return
5594
5425
 
5595
 
        self.add_cleanup(branch.lock_read().unlock)
 
5426
        branch.lock_read()
 
5427
        self.add_cleanup(branch.unlock)
5596
5428
        if revision:
5597
5429
            graph = branch.repository.get_graph()
5598
5430
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
5600
5432
            # only show revisions between revid1 and revid2 (inclusive)
5601
5433
            tags = [(tag, revid) for tag, revid in tags if
5602
5434
                graph.is_between(revid, revid1, revid2)]
5603
 
        if sort is None:
5604
 
            sort = tag_sort_methods.get()
5605
 
        sort(branch, tags)
 
5435
        if sort == 'alpha':
 
5436
            tags.sort()
 
5437
        elif sort == 'time':
 
5438
            timestamps = {}
 
5439
            for tag, revid in tags:
 
5440
                try:
 
5441
                    revobj = branch.repository.get_revision(revid)
 
5442
                except errors.NoSuchRevision:
 
5443
                    timestamp = sys.maxint # place them at the end
 
5444
                else:
 
5445
                    timestamp = revobj.timestamp
 
5446
                timestamps[revid] = timestamp
 
5447
            tags.sort(key=lambda x: timestamps[x[1]])
5606
5448
        if not show_ids:
5607
5449
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5608
5450
            for index, (tag, revid) in enumerate(tags):
5610
5452
                    revno = branch.revision_id_to_dotted_revno(revid)
5611
5453
                    if isinstance(revno, tuple):
5612
5454
                        revno = '.'.join(map(str, revno))
5613
 
                except (errors.NoSuchRevision, errors.GhostRevisionsHaveNoRevno):
 
5455
                except errors.NoSuchRevision:
5614
5456
                    # Bad tag data/merges can lead to tagged revisions
5615
5457
                    # which are not in this branch. Fail gracefully ...
5616
5458
                    revno = '?'
5674
5516
            unstacked=None):
5675
5517
        directory = bzrdir.BzrDir.open(location)
5676
5518
        if stacked_on and unstacked:
5677
 
            raise errors.BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5519
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5678
5520
        elif stacked_on is not None:
5679
5521
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5680
5522
        elif unstacked:
5735
5577
    """
5736
5578
 
5737
5579
    takes_args = ['to_location?']
5738
 
    takes_options = ['directory',
5739
 
                     Option('force',
 
5580
    takes_options = [Option('force',
5740
5581
                        help='Switch even if local commits will be lost.'),
5741
5582
                     'revision',
5742
5583
                     Option('create-branch', short_name='b',
5745
5586
                    ]
5746
5587
 
5747
5588
    def run(self, to_location=None, force=False, create_branch=False,
5748
 
            revision=None, directory=u'.'):
 
5589
            revision=None):
5749
5590
        from bzrlib import switch
5750
 
        tree_location = directory
 
5591
        tree_location = '.'
5751
5592
        revision = _get_one_revision('switch', revision)
5752
5593
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5753
5594
        if to_location is None:
5754
5595
            if revision is None:
5755
5596
                raise errors.BzrCommandError('You must supply either a'
5756
5597
                                             ' revision or a location')
5757
 
            to_location = tree_location
 
5598
            to_location = '.'
5758
5599
        try:
5759
5600
            branch = control_dir.open_branch()
5760
5601
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5895
5736
            name=None,
5896
5737
            switch=None,
5897
5738
            ):
5898
 
        tree, file_list = WorkingTree.open_containing_paths(file_list,
5899
 
            apply_view=False)
 
5739
        tree, file_list = tree_files(file_list, apply_view=False)
5900
5740
        current_view, view_dict = tree.views.get_view_info()
5901
5741
        if name is None:
5902
5742
            name = current_view
6006
5846
            location = "."
6007
5847
        branch = Branch.open_containing(location)[0]
6008
5848
        branch.bzrdir.destroy_branch()
6009
 
 
 
5849
        
6010
5850
 
6011
5851
class cmd_shelve(Command):
6012
5852
    __doc__ = """Temporarily set aside some changes from the current tree.
6031
5871
 
6032
5872
    You can put multiple items on the shelf, and by default, 'unshelve' will
6033
5873
    restore the most recently shelved changes.
6034
 
 
6035
 
    For complicated changes, it is possible to edit the changes in a separate
6036
 
    editor program to decide what the file remaining in the working copy
6037
 
    should look like.  To do this, add the configuration option
6038
 
 
6039
 
        change_editor = PROGRAM @new_path @old_path
6040
 
 
6041
 
    where @new_path is replaced with the path of the new version of the 
6042
 
    file and @old_path is replaced with the path of the old version of 
6043
 
    the file.  The PROGRAM should save the new file with the desired 
6044
 
    contents of the file in the working tree.
6045
 
        
6046
5874
    """
6047
5875
 
6048
5876
    takes_args = ['file*']
6049
5877
 
6050
5878
    takes_options = [
6051
 
        'directory',
6052
5879
        'revision',
6053
5880
        Option('all', help='Shelve all changes.'),
6054
5881
        'message',
6060
5887
        Option('destroy',
6061
5888
               help='Destroy removed changes instead of shelving them.'),
6062
5889
    ]
6063
 
    _see_also = ['unshelve', 'configuration']
 
5890
    _see_also = ['unshelve']
6064
5891
 
6065
5892
    def run(self, revision=None, all=False, file_list=None, message=None,
6066
 
            writer=None, list=False, destroy=False, directory=None):
 
5893
            writer=None, list=False, destroy=False):
6067
5894
        if list:
6068
 
            return self.run_for_list(directory=directory)
 
5895
            return self.run_for_list()
6069
5896
        from bzrlib.shelf_ui import Shelver
6070
5897
        if writer is None:
6071
5898
            writer = bzrlib.option.diff_writer_registry.get()
6072
5899
        try:
6073
5900
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6074
 
                file_list, message, destroy=destroy, directory=directory)
 
5901
                file_list, message, destroy=destroy)
6075
5902
            try:
6076
5903
                shelver.run()
6077
5904
            finally:
6079
5906
        except errors.UserAbort:
6080
5907
            return 0
6081
5908
 
6082
 
    def run_for_list(self, directory=None):
6083
 
        if directory is None:
6084
 
            directory = u'.'
6085
 
        tree = WorkingTree.open_containing(directory)[0]
6086
 
        self.add_cleanup(tree.lock_read().unlock)
 
5909
    def run_for_list(self):
 
5910
        tree = WorkingTree.open_containing('.')[0]
 
5911
        tree.lock_read()
 
5912
        self.add_cleanup(tree.unlock)
6087
5913
        manager = tree.get_shelf_manager()
6088
5914
        shelves = manager.active_shelves()
6089
5915
        if len(shelves) == 0:
6107
5933
 
6108
5934
    takes_args = ['shelf_id?']
6109
5935
    takes_options = [
6110
 
        'directory',
6111
5936
        RegistryOption.from_kwargs(
6112
5937
            'action', help="The action to perform.",
6113
5938
            enum_switch=False, value_switches=True,
6121
5946
    ]
6122
5947
    _see_also = ['shelve']
6123
5948
 
6124
 
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
5949
    def run(self, shelf_id=None, action='apply'):
6125
5950
        from bzrlib.shelf_ui import Unshelver
6126
 
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
5951
        unshelver = Unshelver.from_args(shelf_id, action)
6127
5952
        try:
6128
5953
            unshelver.run()
6129
5954
        finally:
6145
5970
 
6146
5971
    To check what clean-tree will do, use --dry-run.
6147
5972
    """
6148
 
    takes_options = ['directory',
6149
 
                     Option('ignored', help='Delete all ignored files.'),
6150
 
                     Option('detritus', help='Delete conflict files, merge and revert'
 
5973
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5974
                     Option('detritus', help='Delete conflict files, merge'
6151
5975
                            ' backups, and failed selftest dirs.'),
6152
5976
                     Option('unknown',
6153
5977
                            help='Delete files unknown to bzr (default).'),
6155
5979
                            ' deleting them.'),
6156
5980
                     Option('force', help='Do not prompt before deleting.')]
6157
5981
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6158
 
            force=False, directory=u'.'):
 
5982
            force=False):
6159
5983
        from bzrlib.clean_tree import clean_tree
6160
5984
        if not (unknown or ignored or detritus):
6161
5985
            unknown = True
6162
5986
        if dry_run:
6163
5987
            force = True
6164
 
        clean_tree(directory, unknown=unknown, ignored=ignored,
6165
 
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5988
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5989
                   dry_run=dry_run, no_prompt=force)
6166
5990
 
6167
5991
 
6168
5992
class cmd_reference(Command):
6212
6036
            self.outf.write('%s %s\n' % (path, location))
6213
6037
 
6214
6038
 
6215
 
class cmd_export_pot(Command):
6216
 
    __doc__ = """Export command helps and error messages in po format."""
6217
 
 
6218
 
    hidden = True
6219
 
 
6220
 
    def run(self):
6221
 
        from bzrlib.export_pot import export_pot
6222
 
        export_pot(self.outf)
6223
 
 
6224
 
 
6225
6039
def _register_lazy_builtins():
6226
6040
    # register lazy builtins from other modules; called at startup and should
6227
6041
    # be only called once.
6228
6042
    for (name, aliases, module_name) in [
6229
6043
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6230
 
        ('cmd_config', [], 'bzrlib.config'),
6231
6044
        ('cmd_dpush', [], 'bzrlib.foreign'),
6232
6045
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6233
6046
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6234
6047
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6235
 
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6236
 
        ('cmd_verify_signatures', [],
6237
 
                                        'bzrlib.commit_signature_commands'),
6238
 
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
 
6048
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6239
6049
        ]:
6240
6050
        builtin_command_registry.register_lazy(name, aliases, module_name)