~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-02-03 10:06:19 UTC
  • mfrom: (4999.3.2 apport)
  • Revision ID: pqm@pqm.ubuntu.com-20100203100619-f76bo5y5bd5c14wk
(mbp) use apport to send bugs, not just store them

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2004-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
16
16
 
17
17
"""builtin bzr commands"""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
19
import os
22
20
 
23
 
import bzrlib.bzrdir
24
 
 
25
 
from bzrlib import lazy_import
26
 
lazy_import.lazy_import(globals(), """
 
21
from bzrlib.lazy_import import lazy_import
 
22
lazy_import(globals(), """
 
23
import codecs
27
24
import cStringIO
28
 
import errno
29
25
import sys
30
26
import time
31
27
 
34
30
    bugtracker,
35
31
    bundle,
36
32
    btree_index,
37
 
    controldir,
 
33
    bzrdir,
38
34
    directory_service,
39
35
    delta,
40
 
    config as _mod_config,
 
36
    config,
41
37
    errors,
42
38
    globbing,
43
39
    hooks,
49
45
    rename_map,
50
46
    revision as _mod_revision,
51
47
    static_tuple,
 
48
    symbol_versioning,
52
49
    timestamp,
53
50
    transport,
54
51
    ui,
55
52
    urlutils,
56
53
    views,
57
 
    gpg,
58
54
    )
59
55
from bzrlib.branch import Branch
60
56
from bzrlib.conflicts import ConflictList
61
 
from bzrlib.transport import memory
62
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
63
58
from bzrlib.smtp_connection import SMTPConnection
64
59
from bzrlib.workingtree import WorkingTree
65
 
from bzrlib.i18n import gettext, ngettext
66
60
""")
67
61
 
68
 
from bzrlib.commands import (
69
 
    Command,
70
 
    builtin_command_registry,
71
 
    display_command,
72
 
    )
 
62
from bzrlib.commands import Command, display_command
73
63
from bzrlib.option import (
74
64
    ListOption,
75
65
    Option,
78
68
    _parse_revision_str,
79
69
    )
80
70
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
81
 
from bzrlib import (
82
 
    symbol_versioning,
83
 
    )
84
 
 
85
 
 
86
 
def _get_branch_location(control_dir, possible_transports=None):
87
 
    """Return location of branch for this control dir."""
88
 
    try:
89
 
        this_branch = control_dir.open_branch(
90
 
            possible_transports=possible_transports)
91
 
        # This may be a heavy checkout, where we want the master branch
92
 
        master_location = this_branch.get_bound_location()
93
 
        if master_location is not None:
94
 
            return master_location
95
 
        # If not, use a local sibling
96
 
        return this_branch.base
97
 
    except errors.NotBranchError:
98
 
        format = control_dir.find_branch_format()
99
 
        if getattr(format, 'get_reference', None) is not None:
100
 
            return format.get_reference(control_dir)
101
 
        else:
102
 
            return control_dir.root_transport.base
103
 
 
104
 
 
105
 
def _is_colocated(control_dir, possible_transports=None):
106
 
    """Check if the branch in control_dir is colocated.
107
 
 
108
 
    :param control_dir: Control directory
109
 
    :return: Boolean indicating whether 
110
 
    """
111
 
    # This path is meant to be relative to the existing branch
112
 
    this_url = _get_branch_location(control_dir,
113
 
        possible_transports=possible_transports)
114
 
    # Perhaps the target control dir supports colocated branches?
115
 
    try:
116
 
        root = controldir.ControlDir.open(this_url,
117
 
            possible_transports=possible_transports)
118
 
    except errors.NotBranchError:
119
 
        return (False, this_url)
120
 
    else:
121
 
        try:
122
 
            wt = control_dir.open_workingtree()
123
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
124
 
            return (False, this_url)
125
 
        else:
126
 
            return (
127
 
                root._format.colocated_branches and
128
 
                control_dir.control_url == root.control_url,
129
 
                this_url)
130
 
 
131
 
 
132
 
def lookup_new_sibling_branch(control_dir, location, possible_transports=None):
133
 
    """Lookup the location for a new sibling branch.
134
 
 
135
 
    :param control_dir: Control directory relative to which to look up
136
 
        the name.
137
 
    :param location: Name of the new branch
138
 
    :return: Full location to the new branch
139
 
    """
140
 
    location = directory_service.directories.dereference(location)
141
 
    if '/' not in location and '\\' not in location:
142
 
        (colocated, this_url) = _is_colocated(control_dir, possible_transports)
143
 
 
144
 
        if colocated:
145
 
            return urlutils.join_segment_parameters(this_url,
146
 
                {"branch": urlutils.escape(location)})
147
 
        else:
148
 
            return urlutils.join(this_url, '..', urlutils.escape(location))
149
 
    return location
150
 
 
151
 
 
152
 
def lookup_sibling_branch(control_dir, location, possible_transports=None):
153
 
    """Lookup sibling branch.
154
 
    
155
 
    :param control_dir: Control directory relative to which to lookup the
156
 
        location.
157
 
    :param location: Location to look up
158
 
    :return: branch to open
159
 
    """
160
 
    try:
161
 
        # Perhaps it's a colocated branch?
162
 
        return control_dir.open_branch(location, 
163
 
            possible_transports=possible_transports)
164
 
    except (errors.NotBranchError, errors.NoColocatedBranchSupport):
165
 
        try:
166
 
            return Branch.open(location)
167
 
        except errors.NotBranchError:
168
 
            this_url = _get_branch_location(control_dir)
169
 
            return Branch.open(
170
 
                urlutils.join(
171
 
                    this_url, '..', urlutils.escape(location)))
172
 
 
173
 
 
174
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
 
71
 
 
72
 
175
73
def tree_files(file_list, default_branch=u'.', canonicalize=True,
176
74
    apply_view=True):
177
 
    return internal_tree_files(file_list, default_branch, canonicalize,
178
 
        apply_view)
 
75
    try:
 
76
        return internal_tree_files(file_list, default_branch, canonicalize,
 
77
            apply_view)
 
78
    except errors.FileInWrongBranch, e:
 
79
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
 
80
                                     (e.path, file_list[0]))
179
81
 
180
82
 
181
83
def tree_files_for_add(file_list):
206
108
            if view_files:
207
109
                file_list = view_files
208
110
                view_str = views.view_display_str(view_files)
209
 
                note(gettext("Ignoring files outside view. View is %s") % view_str)
 
111
                note("Ignoring files outside view. View is %s" % view_str)
210
112
    return tree, file_list
211
113
 
212
114
 
214
116
    if revisions is None:
215
117
        return None
216
118
    if len(revisions) != 1:
217
 
        raise errors.BzrCommandError(gettext(
218
 
            'bzr %s --revision takes exactly one revision identifier') % (
 
119
        raise errors.BzrCommandError(
 
120
            'bzr %s --revision takes exactly one revision identifier' % (
219
121
                command_name,))
220
122
    return revisions[0]
221
123
 
245
147
 
246
148
# XXX: Bad function name; should possibly also be a class method of
247
149
# WorkingTree rather than a function.
248
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
249
150
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
250
151
    apply_view=True):
251
152
    """Convert command-line paths to a WorkingTree and relative paths.
252
153
 
253
 
    Deprecated: use WorkingTree.open_containing_paths instead.
254
 
 
255
154
    This is typically used for command-line processors that take one or
256
155
    more filenames, and infer the workingtree that contains them.
257
156
 
267
166
 
268
167
    :return: workingtree, [relative_paths]
269
168
    """
270
 
    return WorkingTree.open_containing_paths(
271
 
        file_list, default_directory='.',
272
 
        canonicalize=True,
273
 
        apply_view=True)
 
169
    if file_list is None or len(file_list) == 0:
 
170
        tree = WorkingTree.open_containing(default_branch)[0]
 
171
        if tree.supports_views() and apply_view:
 
172
            view_files = tree.views.lookup_view()
 
173
            if view_files:
 
174
                file_list = view_files
 
175
                view_str = views.view_display_str(view_files)
 
176
                note("Ignoring files outside view. View is %s" % view_str)
 
177
        return tree, file_list
 
178
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
179
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
180
        apply_view=apply_view)
 
181
 
 
182
 
 
183
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
 
184
    """Convert file_list into a list of relpaths in tree.
 
185
 
 
186
    :param tree: A tree to operate on.
 
187
    :param file_list: A list of user provided paths or None.
 
188
    :param apply_view: if True and a view is set, apply it or check that
 
189
        specified files are within it
 
190
    :return: A list of relative paths.
 
191
    :raises errors.PathNotChild: When a provided path is in a different tree
 
192
        than tree.
 
193
    """
 
194
    if file_list is None:
 
195
        return None
 
196
    if tree.supports_views() and apply_view:
 
197
        view_files = tree.views.lookup_view()
 
198
    else:
 
199
        view_files = []
 
200
    new_list = []
 
201
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
 
202
    # doesn't - fix that up here before we enter the loop.
 
203
    if canonicalize:
 
204
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
 
205
    else:
 
206
        fixer = tree.relpath
 
207
    for filename in file_list:
 
208
        try:
 
209
            relpath = fixer(osutils.dereference_path(filename))
 
210
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
211
                raise errors.FileOutsideView(filename, view_files)
 
212
            new_list.append(relpath)
 
213
        except errors.PathNotChild:
 
214
            raise errors.FileInWrongBranch(tree.branch, filename)
 
215
    return new_list
274
216
 
275
217
 
276
218
def _get_view_info_for_change_reporter(tree):
285
227
    return view_info
286
228
 
287
229
 
288
 
def _open_directory_or_containing_tree_or_branch(filename, directory):
289
 
    """Open the tree or branch containing the specified file, unless
290
 
    the --directory option is used to specify a different branch."""
291
 
    if directory is not None:
292
 
        return (None, Branch.open(directory), filename)
293
 
    return controldir.ControlDir.open_containing_tree_or_branch(filename)
294
 
 
295
 
 
296
230
# TODO: Make sure no commands unconditionally use the working directory as a
297
231
# branch.  If a filename argument is used, the first of them should be used to
298
232
# specify the branch.  (Perhaps this can be factored out into some kind of
300
234
# opens the branch?)
301
235
 
302
236
class cmd_status(Command):
303
 
    __doc__ = """Display status summary.
 
237
    """Display status summary.
304
238
 
305
239
    This reports on versioned and unknown files, reporting them
306
240
    grouped by state.  Possible states are:
326
260
    unknown
327
261
        Not versioned and not matching an ignore pattern.
328
262
 
329
 
    Additionally for directories, symlinks and files with a changed
330
 
    executable bit, Bazaar indicates their type using a trailing
331
 
    character: '/', '@' or '*' respectively. These decorations can be
332
 
    disabled using the '--no-classify' option.
 
263
    Additionally for directories, symlinks and files with an executable
 
264
    bit, Bazaar indicates their type using a trailing character: '/', '@'
 
265
    or '*' respectively.
333
266
 
334
267
    To see ignored files use 'bzr ignored'.  For details on the
335
268
    changes to file texts, use 'bzr diff'.
348
281
    To skip the display of pending merge information altogether, use
349
282
    the no-pending option or specify a file/directory.
350
283
 
351
 
    To compare the working directory to a specific revision, pass a
352
 
    single revision to the revision argument.
353
 
 
354
 
    To see which files have changed in a specific revision, or between
355
 
    two revisions, pass a revision range to the revision argument.
356
 
    This will produce the same results as calling 'bzr diff --summarize'.
 
284
    If a revision argument is given, the status is calculated against
 
285
    that revision, or between two revisions if two are provided.
357
286
    """
358
287
 
359
288
    # TODO: --no-recurse, --recurse options
366
295
                            short_name='V'),
367
296
                     Option('no-pending', help='Don\'t show pending merges.',
368
297
                           ),
369
 
                     Option('no-classify',
370
 
                            help='Do not mark object type using indicator.',
371
 
                           ),
372
298
                     ]
373
299
    aliases = ['st', 'stat']
374
300
 
377
303
 
378
304
    @display_command
379
305
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
380
 
            versioned=False, no_pending=False, verbose=False,
381
 
            no_classify=False):
 
306
            versioned=False, no_pending=False, verbose=False):
382
307
        from bzrlib.status import show_tree_status
383
308
 
384
309
        if revision and len(revision) > 2:
385
 
            raise errors.BzrCommandError(gettext('bzr status --revision takes exactly'
386
 
                                         ' one or two revision specifiers'))
 
310
            raise errors.BzrCommandError('bzr status --revision takes exactly'
 
311
                                         ' one or two revision specifiers')
387
312
 
388
 
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
313
        tree, relfile_list = tree_files(file_list)
389
314
        # Avoid asking for specific files when that is not needed.
390
315
        if relfile_list == ['']:
391
316
            relfile_list = None
398
323
        show_tree_status(tree, show_ids=show_ids,
399
324
                         specific_files=relfile_list, revision=revision,
400
325
                         to_file=self.outf, short=short, versioned=versioned,
401
 
                         show_pending=(not no_pending), verbose=verbose,
402
 
                         classify=not no_classify)
 
326
                         show_pending=(not no_pending), verbose=verbose)
403
327
 
404
328
 
405
329
class cmd_cat_revision(Command):
406
 
    __doc__ = """Write out metadata for a revision.
 
330
    """Write out metadata for a revision.
407
331
 
408
332
    The revision to print can either be specified by a specific
409
333
    revision identifier, or you can use --revision.
411
335
 
412
336
    hidden = True
413
337
    takes_args = ['revision_id?']
414
 
    takes_options = ['directory', 'revision']
 
338
    takes_options = ['revision']
415
339
    # cat-revision is more for frontends so should be exact
416
340
    encoding = 'strict'
417
341
 
418
 
    def print_revision(self, revisions, revid):
419
 
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
420
 
        record = stream.next()
421
 
        if record.storage_kind == 'absent':
422
 
            raise errors.NoSuchRevision(revisions, revid)
423
 
        revtext = record.get_bytes_as('fulltext')
424
 
        self.outf.write(revtext.decode('utf-8'))
425
 
 
426
342
    @display_command
427
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
343
    def run(self, revision_id=None, revision=None):
428
344
        if revision_id is not None and revision is not None:
429
 
            raise errors.BzrCommandError(gettext('You can only supply one of'
430
 
                                         ' revision_id or --revision'))
 
345
            raise errors.BzrCommandError('You can only supply one of'
 
346
                                         ' revision_id or --revision')
431
347
        if revision_id is None and revision is None:
432
 
            raise errors.BzrCommandError(gettext('You must supply either'
433
 
                                         ' --revision or a revision_id'))
434
 
 
435
 
        b = controldir.ControlDir.open_containing_tree_or_branch(directory)[1]
436
 
 
437
 
        revisions = b.repository.revisions
438
 
        if revisions is None:
439
 
            raise errors.BzrCommandError(gettext('Repository %r does not support '
440
 
                'access to raw revision texts'))
441
 
 
442
 
        b.repository.lock_read()
443
 
        try:
444
 
            # TODO: jam 20060112 should cat-revision always output utf-8?
445
 
            if revision_id is not None:
446
 
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
447
 
                try:
448
 
                    self.print_revision(revisions, revision_id)
449
 
                except errors.NoSuchRevision:
450
 
                    msg = gettext("The repository {0} contains no revision {1}.").format(
451
 
                        b.repository.base, revision_id)
452
 
                    raise errors.BzrCommandError(msg)
453
 
            elif revision is not None:
454
 
                for rev in revision:
455
 
                    if rev is None:
456
 
                        raise errors.BzrCommandError(
457
 
                            gettext('You cannot specify a NULL revision.'))
458
 
                    rev_id = rev.as_revision_id(b)
459
 
                    self.print_revision(revisions, rev_id)
460
 
        finally:
461
 
            b.repository.unlock()
462
 
        
 
348
            raise errors.BzrCommandError('You must supply either'
 
349
                                         ' --revision or a revision_id')
 
350
        b = WorkingTree.open_containing(u'.')[0].branch
 
351
 
 
352
        # TODO: jam 20060112 should cat-revision always output utf-8?
 
353
        if revision_id is not None:
 
354
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
 
355
            try:
 
356
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
357
            except errors.NoSuchRevision:
 
358
                msg = "The repository %s contains no revision %s." % (b.repository.base,
 
359
                    revision_id)
 
360
                raise errors.BzrCommandError(msg)
 
361
        elif revision is not None:
 
362
            for rev in revision:
 
363
                if rev is None:
 
364
                    raise errors.BzrCommandError('You cannot specify a NULL'
 
365
                                                 ' revision.')
 
366
                rev_id = rev.as_revision_id(b)
 
367
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
 
368
 
463
369
 
464
370
class cmd_dump_btree(Command):
465
 
    __doc__ = """Dump the contents of a btree index file to stdout.
 
371
    """Dump the contents of a btree index file to stdout.
466
372
 
467
373
    PATH is a btree index file, it can be any URL. This includes things like
468
374
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
516
422
                self.outf.write(page_bytes[:header_end])
517
423
                page_bytes = data
518
424
            self.outf.write('\nPage %d\n' % (page_idx,))
519
 
            if len(page_bytes) == 0:
520
 
                self.outf.write('(empty)\n');
521
 
            else:
522
 
                decomp_bytes = zlib.decompress(page_bytes)
523
 
                self.outf.write(decomp_bytes)
524
 
                self.outf.write('\n')
 
425
            decomp_bytes = zlib.decompress(page_bytes)
 
426
            self.outf.write(decomp_bytes)
 
427
            self.outf.write('\n')
525
428
 
526
429
    def _dump_entries(self, trans, basename):
527
430
        try:
535
438
        for node in bt.iter_all_entries():
536
439
            # Node is made up of:
537
440
            # (index, key, value, [references])
538
 
            try:
539
 
                refs = node[3]
540
 
            except IndexError:
541
 
                refs_as_tuples = None
542
 
            else:
543
 
                refs_as_tuples = static_tuple.as_tuples(refs)
 
441
            refs_as_tuples = static_tuple.as_tuples(node[3])
544
442
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
545
443
            self.outf.write('%s\n' % (as_tuple,))
546
444
 
547
445
 
548
446
class cmd_remove_tree(Command):
549
 
    __doc__ = """Remove the working tree from a given branch/checkout.
 
447
    """Remove the working tree from a given branch/checkout.
550
448
 
551
449
    Since a lightweight checkout is little more than a working tree
552
450
    this will refuse to run against one.
554
452
    To re-create the working tree, use "bzr checkout".
555
453
    """
556
454
    _see_also = ['checkout', 'working-trees']
557
 
    takes_args = ['location*']
 
455
    takes_args = ['location?']
558
456
    takes_options = [
559
457
        Option('force',
560
458
               help='Remove the working tree even if it has '
561
 
                    'uncommitted or shelved changes.'),
 
459
                    'uncommitted changes.'),
562
460
        ]
563
461
 
564
 
    def run(self, location_list, force=False):
565
 
        if not location_list:
566
 
            location_list=['.']
567
 
 
568
 
        for location in location_list:
569
 
            d = controldir.ControlDir.open(location)
570
 
 
571
 
            try:
572
 
                working = d.open_workingtree()
573
 
            except errors.NoWorkingTree:
574
 
                raise errors.BzrCommandError(gettext("No working tree to remove"))
575
 
            except errors.NotLocalUrl:
576
 
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
577
 
                                             " of a remote path"))
578
 
            if not force:
579
 
                if (working.has_changes()):
580
 
                    raise errors.UncommittedChanges(working)
581
 
                if working.get_shelf_manager().last_shelf() is not None:
582
 
                    raise errors.ShelvedChanges(working)
583
 
 
584
 
            if working.user_url != working.branch.user_url:
585
 
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
586
 
                                             " from a lightweight checkout"))
587
 
 
588
 
            d.destroy_workingtree()
589
 
 
590
 
 
591
 
class cmd_repair_workingtree(Command):
592
 
    __doc__ = """Reset the working tree state file.
593
 
 
594
 
    This is not meant to be used normally, but more as a way to recover from
595
 
    filesystem corruption, etc. This rebuilds the working inventory back to a
596
 
    'known good' state. Any new modifications (adding a file, renaming, etc)
597
 
    will be lost, though modified files will still be detected as such.
598
 
 
599
 
    Most users will want something more like "bzr revert" or "bzr update"
600
 
    unless the state file has become corrupted.
601
 
 
602
 
    By default this attempts to recover the current state by looking at the
603
 
    headers of the state file. If the state file is too corrupted to even do
604
 
    that, you can supply --revision to force the state of the tree.
605
 
    """
606
 
 
607
 
    takes_options = ['revision', 'directory',
608
 
        Option('force',
609
 
               help='Reset the tree even if it doesn\'t appear to be'
610
 
                    ' corrupted.'),
611
 
    ]
612
 
    hidden = True
613
 
 
614
 
    def run(self, revision=None, directory='.', force=False):
615
 
        tree, _ = WorkingTree.open_containing(directory)
616
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
462
    def run(self, location='.', force=False):
 
463
        d = bzrdir.BzrDir.open(location)
 
464
 
 
465
        try:
 
466
            working = d.open_workingtree()
 
467
        except errors.NoWorkingTree:
 
468
            raise errors.BzrCommandError("No working tree to remove")
 
469
        except errors.NotLocalUrl:
 
470
            raise errors.BzrCommandError("You cannot remove the working tree"
 
471
                                         " of a remote path")
617
472
        if not force:
618
 
            try:
619
 
                tree.check_state()
620
 
            except errors.BzrError:
621
 
                pass # There seems to be a real error here, so we'll reset
622
 
            else:
623
 
                # Refuse
624
 
                raise errors.BzrCommandError(gettext(
625
 
                    'The tree does not appear to be corrupt. You probably'
626
 
                    ' want "bzr revert" instead. Use "--force" if you are'
627
 
                    ' sure you want to reset the working tree.'))
628
 
        if revision is None:
629
 
            revision_ids = None
630
 
        else:
631
 
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
632
 
        try:
633
 
            tree.reset_state(revision_ids)
634
 
        except errors.BzrError, e:
635
 
            if revision_ids is None:
636
 
                extra = (gettext(', the header appears corrupt, try passing -r -1'
637
 
                         ' to set the state to the last commit'))
638
 
            else:
639
 
                extra = ''
640
 
            raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
 
473
            if (working.has_changes()):
 
474
                raise errors.UncommittedChanges(working)
 
475
 
 
476
        working_path = working.bzrdir.root_transport.base
 
477
        branch_path = working.branch.bzrdir.root_transport.base
 
478
        if working_path != branch_path:
 
479
            raise errors.BzrCommandError("You cannot remove the working tree"
 
480
                                         " from a lightweight checkout")
 
481
 
 
482
        d.destroy_workingtree()
641
483
 
642
484
 
643
485
class cmd_revno(Command):
644
 
    __doc__ = """Show current revision number.
 
486
    """Show current revision number.
645
487
 
646
488
    This is equal to the number of revisions on this branch.
647
489
    """
649
491
    _see_also = ['info']
650
492
    takes_args = ['location?']
651
493
    takes_options = [
652
 
        Option('tree', help='Show revno of working tree.'),
653
 
        'revision',
 
494
        Option('tree', help='Show revno of working tree'),
654
495
        ]
655
496
 
656
497
    @display_command
657
 
    def run(self, tree=False, location=u'.', revision=None):
658
 
        if revision is not None and tree:
659
 
            raise errors.BzrCommandError(gettext("--tree and --revision can "
660
 
                "not be used together"))
661
 
 
 
498
    def run(self, tree=False, location=u'.'):
662
499
        if tree:
663
500
            try:
664
501
                wt = WorkingTree.open_containing(location)[0]
665
 
                self.add_cleanup(wt.lock_read().unlock)
 
502
                wt.lock_read()
666
503
            except (errors.NoWorkingTree, errors.NotLocalUrl):
667
504
                raise errors.NoWorkingTree(location)
668
 
            b = wt.branch
 
505
            self.add_cleanup(wt.unlock)
669
506
            revid = wt.last_revision()
 
507
            try:
 
508
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
509
            except errors.NoSuchRevision:
 
510
                revno_t = ('???',)
 
511
            revno = ".".join(str(n) for n in revno_t)
670
512
        else:
671
513
            b = Branch.open_containing(location)[0]
672
 
            self.add_cleanup(b.lock_read().unlock)
673
 
            if revision:
674
 
                if len(revision) != 1:
675
 
                    raise errors.BzrCommandError(gettext(
676
 
                        "Tags can only be placed on a single revision, "
677
 
                        "not on a range"))
678
 
                revid = revision[0].as_revision_id(b)
679
 
            else:
680
 
                revid = b.last_revision()
681
 
        try:
682
 
            revno_t = b.revision_id_to_dotted_revno(revid)
683
 
        except errors.NoSuchRevision:
684
 
            revno_t = ('???',)
685
 
        revno = ".".join(str(n) for n in revno_t)
 
514
            b.lock_read()
 
515
            self.add_cleanup(b.unlock)
 
516
            revno = b.revno()
686
517
        self.cleanup_now()
687
 
        self.outf.write(revno + '\n')
 
518
        self.outf.write(str(revno) + '\n')
688
519
 
689
520
 
690
521
class cmd_revision_info(Command):
691
 
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
522
    """Show revision number and revision id for a given revision identifier.
692
523
    """
693
524
    hidden = True
694
525
    takes_args = ['revision_info*']
695
526
    takes_options = [
696
527
        'revision',
697
 
        custom_help('directory',
 
528
        Option('directory',
698
529
            help='Branch to examine, '
699
 
                 'rather than the one containing the working directory.'),
700
 
        Option('tree', help='Show revno of working tree.'),
 
530
                 'rather than the one containing the working directory.',
 
531
            short_name='d',
 
532
            type=unicode,
 
533
            ),
 
534
        Option('tree', help='Show revno of working tree'),
701
535
        ]
702
536
 
703
537
    @display_command
707
541
        try:
708
542
            wt = WorkingTree.open_containing(directory)[0]
709
543
            b = wt.branch
710
 
            self.add_cleanup(wt.lock_read().unlock)
 
544
            wt.lock_read()
 
545
            self.add_cleanup(wt.unlock)
711
546
        except (errors.NoWorkingTree, errors.NotLocalUrl):
712
547
            wt = None
713
548
            b = Branch.open_containing(directory)[0]
714
 
            self.add_cleanup(b.lock_read().unlock)
 
549
            b.lock_read()
 
550
            self.add_cleanup(b.unlock)
715
551
        revision_ids = []
716
552
        if revision is not None:
717
553
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
745
581
 
746
582
 
747
583
class cmd_add(Command):
748
 
    __doc__ = """Add specified files or directories.
 
584
    """Add specified files or directories.
749
585
 
750
586
    In non-recursive mode, all the named items are added, regardless
751
587
    of whether they were previously ignored.  A warning is given if
759
595
    are added.  This search proceeds recursively into versioned
760
596
    directories.  If no names are given '.' is assumed.
761
597
 
762
 
    A warning will be printed when nested trees are encountered,
763
 
    unless they are explicitly ignored.
764
 
 
765
598
    Therefore simply saying 'bzr add' will version all files that
766
599
    are currently unknown.
767
600
 
783
616
    
784
617
    Any files matching patterns in the ignore list will not be added
785
618
    unless they are explicitly mentioned.
786
 
    
787
 
    In recursive mode, files larger than the configuration option 
788
 
    add.maximum_file_size will be skipped. Named items are never skipped due
789
 
    to file size.
790
619
    """
791
620
    takes_args = ['file*']
792
621
    takes_options = [
819
648
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
820
649
                          to_file=self.outf, should_print=(not is_quiet()))
821
650
        else:
822
 
            action = bzrlib.add.AddWithSkipLargeAction(to_file=self.outf,
 
651
            action = bzrlib.add.AddAction(to_file=self.outf,
823
652
                should_print=(not is_quiet()))
824
653
 
825
654
        if base_tree:
826
 
            self.add_cleanup(base_tree.lock_read().unlock)
 
655
            base_tree.lock_read()
 
656
            self.add_cleanup(base_tree.unlock)
827
657
        tree, file_list = tree_files_for_add(file_list)
828
658
        added, ignored = tree.smart_add(file_list, not
829
659
            no_recurse, action=action, save=not dry_run)
832
662
            if verbose:
833
663
                for glob in sorted(ignored.keys()):
834
664
                    for path in ignored[glob]:
835
 
                        self.outf.write(
836
 
                         gettext("ignored {0} matching \"{1}\"\n").format(
837
 
                         path, glob))
 
665
                        self.outf.write("ignored %s matching \"%s\"\n"
 
666
                                        % (path, glob))
838
667
 
839
668
 
840
669
class cmd_mkdir(Command):
841
 
    __doc__ = """Create a new versioned directory.
 
670
    """Create a new versioned directory.
842
671
 
843
672
    This is equivalent to creating the directory and then adding it.
844
673
    """
845
674
 
846
675
    takes_args = ['dir+']
847
 
    takes_options = [
848
 
        Option(
849
 
            'parents',
850
 
            help='No error if existing, make parent directories as needed.',
851
 
            short_name='p'
852
 
            )
853
 
        ]
854
676
    encoding_type = 'replace'
855
677
 
856
 
    @classmethod
857
 
    def add_file_with_parents(cls, wt, relpath):
858
 
        if wt.path2id(relpath) is not None:
859
 
            return
860
 
        cls.add_file_with_parents(wt, osutils.dirname(relpath))
861
 
        wt.add([relpath])
862
 
 
863
 
    @classmethod
864
 
    def add_file_single(cls, wt, relpath):
865
 
        wt.add([relpath])
866
 
 
867
 
    def run(self, dir_list, parents=False):
868
 
        if parents:
869
 
            add_file = self.add_file_with_parents
870
 
        else:
871
 
            add_file = self.add_file_single
872
 
        for dir in dir_list:
873
 
            wt, relpath = WorkingTree.open_containing(dir)
874
 
            if parents:
875
 
                try:
876
 
                    os.makedirs(dir)
877
 
                except OSError, e:
878
 
                    if e.errno != errno.EEXIST:
879
 
                        raise
880
 
            else:
881
 
                os.mkdir(dir)
882
 
            add_file(wt, relpath)
883
 
            if not is_quiet():
884
 
                self.outf.write(gettext('added %s\n') % dir)
 
678
    def run(self, dir_list):
 
679
        for d in dir_list:
 
680
            os.mkdir(d)
 
681
            wt, dd = WorkingTree.open_containing(d)
 
682
            wt.add([dd])
 
683
            self.outf.write('added %s\n' % d)
885
684
 
886
685
 
887
686
class cmd_relpath(Command):
888
 
    __doc__ = """Show path of a file relative to root"""
 
687
    """Show path of a file relative to root"""
889
688
 
890
689
    takes_args = ['filename']
891
690
    hidden = True
900
699
 
901
700
 
902
701
class cmd_inventory(Command):
903
 
    __doc__ = """Show inventory of the current working copy or a revision.
 
702
    """Show inventory of the current working copy or a revision.
904
703
 
905
704
    It is possible to limit the output to a particular entry
906
705
    type using the --kind option.  For example: --kind file.
923
722
    @display_command
924
723
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
925
724
        if kind and kind not in ['file', 'directory', 'symlink']:
926
 
            raise errors.BzrCommandError(gettext('invalid kind %r specified') % (kind,))
 
725
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
927
726
 
928
727
        revision = _get_one_revision('inventory', revision)
929
 
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
930
 
        self.add_cleanup(work_tree.lock_read().unlock)
 
728
        work_tree, file_list = tree_files(file_list)
 
729
        work_tree.lock_read()
 
730
        self.add_cleanup(work_tree.unlock)
931
731
        if revision is not None:
932
732
            tree = revision.as_tree(work_tree.branch)
933
733
 
934
734
            extra_trees = [work_tree]
935
 
            self.add_cleanup(tree.lock_read().unlock)
 
735
            tree.lock_read()
 
736
            self.add_cleanup(tree.unlock)
936
737
        else:
937
738
            tree = work_tree
938
739
            extra_trees = []
939
740
 
940
 
        self.add_cleanup(tree.lock_read().unlock)
941
741
        if file_list is not None:
942
742
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
943
743
                                      require_versioned=True)
944
744
            # find_ids_across_trees may include some paths that don't
945
745
            # exist in 'tree'.
946
 
            entries = tree.iter_entries_by_dir(specific_file_ids=file_ids)
 
746
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
747
                             for file_id in file_ids if file_id in tree)
947
748
        else:
948
 
            entries = tree.iter_entries_by_dir()
 
749
            entries = tree.inventory.entries()
949
750
 
950
 
        for path, entry in sorted(entries):
 
751
        self.cleanup_now()
 
752
        for path, entry in entries:
951
753
            if kind and kind != entry.kind:
952
754
                continue
953
 
            if path == "":
954
 
                continue
955
755
            if show_ids:
956
756
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
957
757
            else:
960
760
 
961
761
 
962
762
class cmd_mv(Command):
963
 
    __doc__ = """Move or rename a file.
 
763
    """Move or rename a file.
964
764
 
965
765
    :Usage:
966
766
        bzr mv OLDNAME NEWNAME
993
793
        if auto:
994
794
            return self.run_auto(names_list, after, dry_run)
995
795
        elif dry_run:
996
 
            raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
 
796
            raise errors.BzrCommandError('--dry-run requires --auto.')
997
797
        if names_list is None:
998
798
            names_list = []
999
799
        if len(names_list) < 2:
1000
 
            raise errors.BzrCommandError(gettext("missing file argument"))
1001
 
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
1002
 
        for file_name in rel_names[0:-1]:
1003
 
            if file_name == '':
1004
 
                raise errors.BzrCommandError(gettext("can not move root of branch"))
1005
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
800
            raise errors.BzrCommandError("missing file argument")
 
801
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
802
        tree.lock_tree_write()
 
803
        self.add_cleanup(tree.unlock)
1006
804
        self._run(tree, names_list, rel_names, after)
1007
805
 
1008
806
    def run_auto(self, names_list, after, dry_run):
1009
807
        if names_list is not None and len(names_list) > 1:
1010
 
            raise errors.BzrCommandError(gettext('Only one path may be specified to'
1011
 
                                         ' --auto.'))
 
808
            raise errors.BzrCommandError('Only one path may be specified to'
 
809
                                         ' --auto.')
1012
810
        if after:
1013
 
            raise errors.BzrCommandError(gettext('--after cannot be specified with'
1014
 
                                         ' --auto.'))
1015
 
        work_tree, file_list = WorkingTree.open_containing_paths(
1016
 
            names_list, default_directory='.')
1017
 
        self.add_cleanup(work_tree.lock_tree_write().unlock)
 
811
            raise errors.BzrCommandError('--after cannot be specified with'
 
812
                                         ' --auto.')
 
813
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
814
        work_tree.lock_tree_write()
 
815
        self.add_cleanup(work_tree.unlock)
1018
816
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
1019
817
 
1020
818
    def _run(self, tree, names_list, rel_names, after):
1029
827
                and rel_names[0].lower() == rel_names[1].lower()):
1030
828
                into_existing = False
1031
829
            else:
 
830
                inv = tree.inventory
1032
831
                # 'fix' the case of a potential 'from'
1033
832
                from_id = tree.path2id(
1034
833
                            tree.get_canonical_inventory_path(rel_names[0]))
1035
834
                if (not osutils.lexists(names_list[0]) and
1036
 
                    from_id and tree.stored_kind(from_id) == "directory"):
 
835
                    from_id and inv.get_file_kind(from_id) == "directory"):
1037
836
                    into_existing = False
1038
837
        # move/rename
1039
838
        if into_existing:
1046
845
                    self.outf.write("%s => %s\n" % (src, dest))
1047
846
        else:
1048
847
            if len(names_list) != 2:
1049
 
                raise errors.BzrCommandError(gettext('to mv multiple files the'
 
848
                raise errors.BzrCommandError('to mv multiple files the'
1050
849
                                             ' destination must be a versioned'
1051
 
                                             ' directory'))
 
850
                                             ' directory')
1052
851
 
1053
852
            # for cicp file-systems: the src references an existing inventory
1054
853
            # item:
1098
897
 
1099
898
 
1100
899
class cmd_pull(Command):
1101
 
    __doc__ = """Turn this branch into a mirror of another branch.
 
900
    """Turn this branch into a mirror of another branch.
1102
901
 
1103
902
    By default, this command only works on branches that have not diverged.
1104
903
    Branches are considered diverged if the destination branch's most recent 
1113
912
    match the remote one, use pull --overwrite. This will work even if the two
1114
913
    branches have diverged.
1115
914
 
1116
 
    If there is no default location set, the first pull will set it (use
1117
 
    --no-remember to avoid setting it). After that, you can omit the
1118
 
    location to use the default.  To change the default, use --remember. The
1119
 
    value will only be saved if the remote location can be accessed.
1120
 
 
1121
 
    The --verbose option will display the revisions pulled using the log_format
1122
 
    configuration option. You can use a different format by overriding it with
1123
 
    -Olog_format=<other_format>.
 
915
    If there is no default location set, the first pull will set it.  After
 
916
    that, you can omit the location to use the default.  To change the
 
917
    default, use --remember. The value will only be saved if the remote
 
918
    location can be accessed.
1124
919
 
1125
920
    Note: The location can be specified either in the form of a branch,
1126
921
    or in the form of a path to a file containing a merge directive generated
1131
926
    takes_options = ['remember', 'overwrite', 'revision',
1132
927
        custom_help('verbose',
1133
928
            help='Show logs of pulled revisions.'),
1134
 
        custom_help('directory',
 
929
        Option('directory',
1135
930
            help='Branch to pull into, '
1136
 
                 'rather than the one containing the working directory.'),
 
931
                 'rather than the one containing the working directory.',
 
932
            short_name='d',
 
933
            type=unicode,
 
934
            ),
1137
935
        Option('local',
1138
936
            help="Perform a local pull in a bound "
1139
937
                 "branch.  Local pulls are not applied to "
1140
938
                 "the master branch."
1141
939
            ),
1142
 
        Option('show-base',
1143
 
            help="Show base revision text in conflicts.")
1144
940
        ]
1145
941
    takes_args = ['location?']
1146
942
    encoding_type = 'replace'
1147
943
 
1148
 
    def run(self, location=None, remember=None, overwrite=False,
 
944
    def run(self, location=None, remember=False, overwrite=False,
1149
945
            revision=None, verbose=False,
1150
 
            directory=None, local=False,
1151
 
            show_base=False):
 
946
            directory=None, local=False):
1152
947
        # FIXME: too much stuff is in the command class
1153
948
        revision_id = None
1154
949
        mergeable = None
1157
952
        try:
1158
953
            tree_to = WorkingTree.open_containing(directory)[0]
1159
954
            branch_to = tree_to.branch
1160
 
            self.add_cleanup(tree_to.lock_write().unlock)
1161
955
        except errors.NoWorkingTree:
1162
956
            tree_to = None
1163
957
            branch_to = Branch.open_containing(directory)[0]
1164
 
            self.add_cleanup(branch_to.lock_write().unlock)
1165
 
 
1166
 
        if tree_to is None and show_base:
1167
 
            raise errors.BzrCommandError(gettext("Need working tree for --show-base."))
1168
 
 
 
958
        
1169
959
        if local and not branch_to.get_bound_location():
1170
960
            raise errors.LocalRequiresBoundBranch()
1171
961
 
1180
970
        stored_loc = branch_to.get_parent()
1181
971
        if location is None:
1182
972
            if stored_loc is None:
1183
 
                raise errors.BzrCommandError(gettext("No pull location known or"
1184
 
                                             " specified."))
 
973
                raise errors.BzrCommandError("No pull location known or"
 
974
                                             " specified.")
1185
975
            else:
1186
976
                display_url = urlutils.unescape_for_display(stored_loc,
1187
977
                        self.outf.encoding)
1188
978
                if not is_quiet():
1189
 
                    self.outf.write(gettext("Using saved parent location: %s\n") % display_url)
 
979
                    self.outf.write("Using saved parent location: %s\n" % display_url)
1190
980
                location = stored_loc
1191
981
 
1192
982
        revision = _get_one_revision('pull', revision)
1193
983
        if mergeable is not None:
1194
984
            if revision is not None:
1195
 
                raise errors.BzrCommandError(gettext(
1196
 
                    'Cannot use -r with merge directives or bundles'))
 
985
                raise errors.BzrCommandError(
 
986
                    'Cannot use -r with merge directives or bundles')
1197
987
            mergeable.install_revisions(branch_to.repository)
1198
988
            base_revision_id, revision_id, verified = \
1199
989
                mergeable.get_merge_request(branch_to.repository)
1201
991
        else:
1202
992
            branch_from = Branch.open(location,
1203
993
                possible_transports=possible_transports)
1204
 
            self.add_cleanup(branch_from.lock_read().unlock)
1205
 
            # Remembers if asked explicitly or no previous location is set
1206
 
            if (remember
1207
 
                or (remember is None and branch_to.get_parent() is None)):
 
994
 
 
995
            if branch_to.get_parent() is None or remember:
1208
996
                branch_to.set_parent(branch_from.base)
1209
997
 
 
998
        if branch_from is not branch_to:
 
999
            branch_from.lock_read()
 
1000
            self.add_cleanup(branch_from.unlock)
1210
1001
        if revision is not None:
1211
1002
            revision_id = revision.as_revision_id(branch_from)
1212
1003
 
 
1004
        branch_to.lock_write()
 
1005
        self.add_cleanup(branch_to.unlock)
1213
1006
        if tree_to is not None:
1214
1007
            view_info = _get_view_info_for_change_reporter(tree_to)
1215
1008
            change_reporter = delta._ChangeReporter(
1217
1010
                view_info=view_info)
1218
1011
            result = tree_to.pull(
1219
1012
                branch_from, overwrite, revision_id, change_reporter,
1220
 
                local=local, show_base=show_base)
 
1013
                possible_transports=possible_transports, local=local)
1221
1014
        else:
1222
1015
            result = branch_to.pull(
1223
1016
                branch_from, overwrite, revision_id, local=local)
1227
1020
            log.show_branch_change(
1228
1021
                branch_to, self.outf, result.old_revno,
1229
1022
                result.old_revid)
1230
 
        if getattr(result, 'tag_conflicts', None):
1231
 
            return 1
1232
 
        else:
1233
 
            return 0
1234
1023
 
1235
1024
 
1236
1025
class cmd_push(Command):
1237
 
    __doc__ = """Update a mirror of this branch.
 
1026
    """Update a mirror of this branch.
1238
1027
 
1239
1028
    The target branch will not have its working tree populated because this
1240
1029
    is both expensive, and is not supported on remote file systems.
1253
1042
    do a merge (see bzr help merge) from the other branch, and commit that.
1254
1043
    After that you will be able to do a push without '--overwrite'.
1255
1044
 
1256
 
    If there is no default push location set, the first push will set it (use
1257
 
    --no-remember to avoid setting it).  After that, you can omit the
1258
 
    location to use the default.  To change the default, use --remember. The
1259
 
    value will only be saved if the remote location can be accessed.
1260
 
 
1261
 
    The --verbose option will display the revisions pushed using the log_format
1262
 
    configuration option. You can use a different format by overriding it with
1263
 
    -Olog_format=<other_format>.
 
1045
    If there is no default push location set, the first push will set it.
 
1046
    After that, you can omit the location to use the default.  To change the
 
1047
    default, use --remember. The value will only be saved if the remote
 
1048
    location can be accessed.
1264
1049
    """
1265
1050
 
1266
1051
    _see_also = ['pull', 'update', 'working-trees']
1268
1053
        Option('create-prefix',
1269
1054
               help='Create the path leading up to the branch '
1270
1055
                    'if it does not already exist.'),
1271
 
        custom_help('directory',
 
1056
        Option('directory',
1272
1057
            help='Branch to push from, '
1273
 
                 'rather than the one containing the working directory.'),
 
1058
                 'rather than the one containing the working directory.',
 
1059
            short_name='d',
 
1060
            type=unicode,
 
1061
            ),
1274
1062
        Option('use-existing-dir',
1275
1063
               help='By default push will fail if the target'
1276
1064
                    ' directory exists, but does not already'
1287
1075
        Option('strict',
1288
1076
               help='Refuse to push if there are uncommitted changes in'
1289
1077
               ' the working tree, --no-strict disables the check.'),
1290
 
        Option('no-tree',
1291
 
               help="Don't populate the working tree, even for protocols"
1292
 
               " that support it."),
1293
1078
        ]
1294
1079
    takes_args = ['location?']
1295
1080
    encoding_type = 'replace'
1296
1081
 
1297
 
    def run(self, location=None, remember=None, overwrite=False,
 
1082
    def run(self, location=None, remember=False, overwrite=False,
1298
1083
        create_prefix=False, verbose=False, revision=None,
1299
1084
        use_existing_dir=False, directory=None, stacked_on=None,
1300
 
        stacked=False, strict=None, no_tree=False):
 
1085
        stacked=False, strict=None):
1301
1086
        from bzrlib.push import _show_push_branch
1302
1087
 
1303
1088
        if directory is None:
1304
1089
            directory = '.'
1305
1090
        # Get the source branch
1306
1091
        (tree, br_from,
1307
 
         _unused) = controldir.ControlDir.open_containing_tree_or_branch(directory)
 
1092
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1093
        if strict is None:
 
1094
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
 
1095
        if strict is None: strict = True # default value
1308
1096
        # Get the tip's revision_id
1309
1097
        revision = _get_one_revision('push', revision)
1310
1098
        if revision is not None:
1311
1099
            revision_id = revision.in_history(br_from).rev_id
1312
1100
        else:
1313
1101
            revision_id = None
1314
 
        if tree is not None and revision_id is None:
1315
 
            tree.check_changed_or_out_of_date(
1316
 
                strict, 'push_strict',
1317
 
                more_error='Use --no-strict to force the push.',
1318
 
                more_warning='Uncommitted changes will not be pushed.')
 
1102
        if strict and tree is not None and revision_id is None:
 
1103
            if (tree.has_changes()):
 
1104
                raise errors.UncommittedChanges(
 
1105
                    tree, more='Use --no-strict to force the push.')
 
1106
            if tree.last_revision() != tree.branch.last_revision():
 
1107
                # The tree has lost sync with its branch, there is little
 
1108
                # chance that the user is aware of it but he can still force
 
1109
                # the push with --no-strict
 
1110
                raise errors.OutOfDateTree(
 
1111
                    tree, more='Use --no-strict to force the push.')
 
1112
 
1319
1113
        # Get the stacked_on branch, if any
1320
1114
        if stacked_on is not None:
1321
1115
            stacked_on = urlutils.normalize_url(stacked_on)
1331
1125
                    # error by the feedback given to them. RBC 20080227.
1332
1126
                    stacked_on = parent_url
1333
1127
            if not stacked_on:
1334
 
                raise errors.BzrCommandError(gettext(
1335
 
                    "Could not determine branch to refer to."))
 
1128
                raise errors.BzrCommandError(
 
1129
                    "Could not determine branch to refer to.")
1336
1130
 
1337
1131
        # Get the destination location
1338
1132
        if location is None:
1339
1133
            stored_loc = br_from.get_push_location()
1340
1134
            if stored_loc is None:
1341
 
                parent_loc = br_from.get_parent()
1342
 
                if parent_loc:
1343
 
                    raise errors.BzrCommandError(gettext(
1344
 
                        "No push location known or specified. To push to the "
1345
 
                        "parent branch (at %s), use 'bzr push :parent'." %
1346
 
                        urlutils.unescape_for_display(parent_loc,
1347
 
                            self.outf.encoding)))
1348
 
                else:
1349
 
                    raise errors.BzrCommandError(gettext(
1350
 
                        "No push location known or specified."))
 
1135
                raise errors.BzrCommandError(
 
1136
                    "No push location known or specified.")
1351
1137
            else:
1352
1138
                display_url = urlutils.unescape_for_display(stored_loc,
1353
1139
                        self.outf.encoding)
1354
 
                note(gettext("Using saved push location: %s") % display_url)
 
1140
                self.outf.write("Using saved push location: %s\n" % display_url)
1355
1141
                location = stored_loc
1356
1142
 
1357
1143
        _show_push_branch(br_from, revision_id, location, self.outf,
1358
1144
            verbose=verbose, overwrite=overwrite, remember=remember,
1359
1145
            stacked_on=stacked_on, create_prefix=create_prefix,
1360
 
            use_existing_dir=use_existing_dir, no_tree=no_tree)
 
1146
            use_existing_dir=use_existing_dir)
1361
1147
 
1362
1148
 
1363
1149
class cmd_branch(Command):
1364
 
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
1150
    """Create a new branch that is a copy of an existing branch.
1365
1151
 
1366
1152
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1367
1153
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1372
1158
 
1373
1159
    To retrieve the branch as of a particular revision, supply the --revision
1374
1160
    parameter, as in "branch foo/bar -r 5".
1375
 
 
1376
 
    The synonyms 'clone' and 'get' for this command are deprecated.
1377
1161
    """
1378
1162
 
1379
1163
    _see_also = ['checkout']
1380
1164
    takes_args = ['from_location', 'to_location?']
1381
 
    takes_options = ['revision',
1382
 
        Option('hardlink', help='Hard-link working tree files where possible.'),
1383
 
        Option('files-from', type=str,
1384
 
               help="Get file contents from this tree."),
 
1165
    takes_options = ['revision', Option('hardlink',
 
1166
        help='Hard-link working tree files where possible.'),
1385
1167
        Option('no-tree',
1386
1168
            help="Create a branch without a working-tree."),
1387
1169
        Option('switch',
1405
1187
 
1406
1188
    def run(self, from_location, to_location=None, revision=None,
1407
1189
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1408
 
            use_existing_dir=False, switch=False, bind=False,
1409
 
            files_from=None):
 
1190
            use_existing_dir=False, switch=False, bind=False):
1410
1191
        from bzrlib import switch as _mod_switch
1411
1192
        from bzrlib.tag import _merge_tags_if_possible
1412
 
        if self.invoked_as in ['get', 'clone']:
1413
 
            ui.ui_factory.show_user_warning(
1414
 
                'deprecated_command',
1415
 
                deprecated_name=self.invoked_as,
1416
 
                recommended_name='branch',
1417
 
                deprecated_in_version='2.4')
1418
 
        accelerator_tree, br_from = controldir.ControlDir.open_tree_or_branch(
 
1193
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1419
1194
            from_location)
1420
 
        if not (hardlink or files_from):
1421
 
            # accelerator_tree is usually slower because you have to read N
1422
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1423
 
            # explicitly request it
1424
 
            accelerator_tree = None
1425
 
        if files_from is not None and files_from != from_location:
1426
 
            accelerator_tree = WorkingTree.open(files_from)
1427
1195
        revision = _get_one_revision('branch', revision)
1428
 
        self.add_cleanup(br_from.lock_read().unlock)
 
1196
        br_from.lock_read()
 
1197
        self.add_cleanup(br_from.unlock)
1429
1198
        if revision is not None:
1430
1199
            revision_id = revision.as_revision_id(br_from)
1431
1200
        else:
1434
1203
            # RBC 20060209
1435
1204
            revision_id = br_from.last_revision()
1436
1205
        if to_location is None:
1437
 
            to_location = getattr(br_from, "name", None)
1438
 
            if not to_location:
1439
 
                to_location = urlutils.derive_to_location(from_location)
 
1206
            to_location = urlutils.derive_to_location(from_location)
1440
1207
        to_transport = transport.get_transport(to_location)
1441
1208
        try:
1442
1209
            to_transport.mkdir('.')
1443
1210
        except errors.FileExists:
1444
 
            try:
1445
 
                to_dir = controldir.ControlDir.open_from_transport(
1446
 
                    to_transport)
1447
 
            except errors.NotBranchError:
1448
 
                if not use_existing_dir:
1449
 
                    raise errors.BzrCommandError(gettext('Target directory "%s" '
1450
 
                        'already exists.') % to_location)
1451
 
                else:
1452
 
                    to_dir = None
 
1211
            if not use_existing_dir:
 
1212
                raise errors.BzrCommandError('Target directory "%s" '
 
1213
                    'already exists.' % to_location)
1453
1214
            else:
1454
1215
                try:
1455
 
                    to_dir.open_branch()
 
1216
                    bzrdir.BzrDir.open_from_transport(to_transport)
1456
1217
                except errors.NotBranchError:
1457
1218
                    pass
1458
1219
                else:
1459
1220
                    raise errors.AlreadyBranchError(to_location)
1460
1221
        except errors.NoSuchFile:
1461
 
            raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
 
1222
            raise errors.BzrCommandError('Parent of "%s" does not exist.'
1462
1223
                                         % to_location)
1463
 
        else:
1464
 
            to_dir = None
1465
 
        if to_dir is None:
1466
 
            try:
1467
 
                # preserve whatever source format we have.
1468
 
                to_dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1469
 
                                            possible_transports=[to_transport],
1470
 
                                            accelerator_tree=accelerator_tree,
1471
 
                                            hardlink=hardlink, stacked=stacked,
1472
 
                                            force_new_repo=standalone,
1473
 
                                            create_tree_if_local=not no_tree,
1474
 
                                            source_branch=br_from)
1475
 
                branch = to_dir.open_branch(
1476
 
                    possible_transports=[
1477
 
                        br_from.bzrdir.root_transport, to_transport])
1478
 
            except errors.NoSuchRevision:
1479
 
                to_transport.delete_tree('.')
1480
 
                msg = gettext("The branch {0} has no revision {1}.").format(
1481
 
                    from_location, revision)
1482
 
                raise errors.BzrCommandError(msg)
1483
 
        else:
1484
 
            try:
1485
 
                to_repo = to_dir.open_repository()
1486
 
            except errors.NoRepositoryPresent:
1487
 
                to_repo = to_dir.create_repository()
1488
 
            to_repo.fetch(br_from.repository, revision_id=revision_id)
1489
 
            branch = br_from.sprout(to_dir, revision_id=revision_id)
 
1224
        try:
 
1225
            # preserve whatever source format we have.
 
1226
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
1227
                                        possible_transports=[to_transport],
 
1228
                                        accelerator_tree=accelerator_tree,
 
1229
                                        hardlink=hardlink, stacked=stacked,
 
1230
                                        force_new_repo=standalone,
 
1231
                                        create_tree_if_local=not no_tree,
 
1232
                                        source_branch=br_from)
 
1233
            branch = dir.open_branch()
 
1234
        except errors.NoSuchRevision:
 
1235
            to_transport.delete_tree('.')
 
1236
            msg = "The branch %s has no revision %s." % (from_location,
 
1237
                revision)
 
1238
            raise errors.BzrCommandError(msg)
1490
1239
        _merge_tags_if_possible(br_from, branch)
1491
1240
        # If the source branch is stacked, the new branch may
1492
1241
        # be stacked whether we asked for that explicitly or not.
1493
1242
        # We therefore need a try/except here and not just 'if stacked:'
1494
1243
        try:
1495
 
            note(gettext('Created new stacked branch referring to %s.') %
 
1244
            note('Created new stacked branch referring to %s.' %
1496
1245
                branch.get_stacked_on_url())
1497
1246
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1498
1247
            errors.UnstackableRepositoryFormat), e:
1499
 
            note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
 
1248
            note('Branched %d revision(s).' % branch.revno())
1500
1249
        if bind:
1501
1250
            # Bind to the parent
1502
1251
            parent_branch = Branch.open(from_location)
1503
1252
            branch.bind(parent_branch)
1504
 
            note(gettext('New branch bound to %s') % from_location)
 
1253
            note('New branch bound to %s' % from_location)
1505
1254
        if switch:
1506
1255
            # Switch to the new branch
1507
1256
            wt, _ = WorkingTree.open_containing('.')
1508
1257
            _mod_switch.switch(wt.bzrdir, branch)
1509
 
            note(gettext('Switched to branch: %s'),
 
1258
            note('Switched to branch: %s',
1510
1259
                urlutils.unescape_for_display(branch.base, 'utf-8'))
1511
1260
 
1512
1261
 
1513
 
class cmd_branches(Command):
1514
 
    __doc__ = """List the branches available at the current location.
1515
 
 
1516
 
    This command will print the names of all the branches at the current
1517
 
    location.
1518
 
    """
1519
 
 
1520
 
    takes_args = ['location?']
1521
 
    takes_options = [
1522
 
                  Option('recursive', short_name='R',
1523
 
                         help='Recursively scan for branches rather than '
1524
 
                              'just looking in the specified location.')]
1525
 
 
1526
 
    def run(self, location=".", recursive=False):
1527
 
        if recursive:
1528
 
            t = transport.get_transport(location)
1529
 
            if not t.listable():
1530
 
                raise errors.BzrCommandError(
1531
 
                    "Can't scan this type of location.")
1532
 
            for b in controldir.ControlDir.find_branches(t):
1533
 
                self.outf.write("%s\n" % urlutils.unescape_for_display(
1534
 
                    urlutils.relative_url(t.base, b.base),
1535
 
                    self.outf.encoding).rstrip("/"))
1536
 
        else:
1537
 
            dir = controldir.ControlDir.open_containing(location)[0]
1538
 
            try:
1539
 
                active_branch = dir.open_branch(name="")
1540
 
            except errors.NotBranchError:
1541
 
                active_branch = None
1542
 
            branches = dir.get_branches()
1543
 
            names = {}
1544
 
            for name, branch in branches.iteritems():
1545
 
                if name == "":
1546
 
                    continue
1547
 
                active = (active_branch is not None and
1548
 
                          active_branch.base == branch.base)
1549
 
                names[name] = active
1550
 
            # Only mention the current branch explicitly if it's not
1551
 
            # one of the colocated branches
1552
 
            if not any(names.values()) and active_branch is not None:
1553
 
                self.outf.write("* %s\n" % gettext("(default)"))
1554
 
            for name in sorted(names.keys()):
1555
 
                active = names[name]
1556
 
                if active:
1557
 
                    prefix = "*"
1558
 
                else:
1559
 
                    prefix = " "
1560
 
                self.outf.write("%s %s\n" % (
1561
 
                    prefix, name.encode(self.outf.encoding)))
1562
 
 
1563
 
 
1564
1262
class cmd_checkout(Command):
1565
 
    __doc__ = """Create a new checkout of an existing branch.
 
1263
    """Create a new checkout of an existing branch.
1566
1264
 
1567
1265
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1568
1266
    the branch found in '.'. This is useful if you have removed the working tree
1605
1303
        if branch_location is None:
1606
1304
            branch_location = osutils.getcwd()
1607
1305
            to_location = branch_location
1608
 
        accelerator_tree, source = controldir.ControlDir.open_tree_or_branch(
 
1306
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1609
1307
            branch_location)
1610
 
        if not (hardlink or files_from):
1611
 
            # accelerator_tree is usually slower because you have to read N
1612
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1613
 
            # explicitly request it
1614
 
            accelerator_tree = None
1615
1308
        revision = _get_one_revision('checkout', revision)
1616
 
        if files_from is not None and files_from != branch_location:
 
1309
        if files_from is not None:
1617
1310
            accelerator_tree = WorkingTree.open(files_from)
1618
1311
        if revision is not None:
1619
1312
            revision_id = revision.as_revision_id(source)
1636
1329
 
1637
1330
 
1638
1331
class cmd_renames(Command):
1639
 
    __doc__ = """Show list of renamed files.
 
1332
    """Show list of renamed files.
1640
1333
    """
1641
1334
    # TODO: Option to show renames between two historical versions.
1642
1335
 
1647
1340
    @display_command
1648
1341
    def run(self, dir=u'.'):
1649
1342
        tree = WorkingTree.open_containing(dir)[0]
1650
 
        self.add_cleanup(tree.lock_read().unlock)
 
1343
        tree.lock_read()
 
1344
        self.add_cleanup(tree.unlock)
1651
1345
        new_inv = tree.inventory
1652
1346
        old_tree = tree.basis_tree()
1653
 
        self.add_cleanup(old_tree.lock_read().unlock)
 
1347
        old_tree.lock_read()
 
1348
        self.add_cleanup(old_tree.unlock)
1654
1349
        old_inv = old_tree.inventory
1655
1350
        renames = []
1656
1351
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1666
1361
 
1667
1362
 
1668
1363
class cmd_update(Command):
1669
 
    __doc__ = """Update a working tree to a new revision.
1670
 
 
1671
 
    This will perform a merge of the destination revision (the tip of the
1672
 
    branch, or the specified revision) into the working tree, and then make
1673
 
    that revision the basis revision for the working tree.  
1674
 
 
1675
 
    You can use this to visit an older revision, or to update a working tree
1676
 
    that is out of date from its branch.
1677
 
    
1678
 
    If there are any uncommitted changes in the tree, they will be carried
1679
 
    across and remain as uncommitted changes after the update.  To discard
1680
 
    these changes, use 'bzr revert'.  The uncommitted changes may conflict
1681
 
    with the changes brought in by the change in basis revision.
1682
 
 
1683
 
    If the tree's branch is bound to a master branch, bzr will also update
 
1364
    """Update a tree to have the latest code committed to its branch.
 
1365
 
 
1366
    This will perform a merge into the working tree, and may generate
 
1367
    conflicts. If you have any local changes, you will still
 
1368
    need to commit them after the update for the update to be complete.
 
1369
 
 
1370
    If you want to discard your local changes, you can just do a
 
1371
    'bzr revert' instead of 'bzr commit' after the update.
 
1372
 
 
1373
    If the tree's branch is bound to a master branch, it will also update
1684
1374
    the branch from the master.
1685
 
 
1686
 
    You cannot update just a single file or directory, because each Bazaar
1687
 
    working tree has just a single basis revision.  If you want to restore a
1688
 
    file that has been removed locally, use 'bzr revert' instead of 'bzr
1689
 
    update'.  If you want to restore a file to its state in a previous
1690
 
    revision, use 'bzr revert' with a '-r' option, or use 'bzr cat' to write
1691
 
    out the old content of that file to a new location.
1692
 
 
1693
 
    The 'dir' argument, if given, must be the location of the root of a
1694
 
    working tree to update.  By default, the working tree that contains the 
1695
 
    current working directory is used.
1696
1375
    """
1697
1376
 
1698
1377
    _see_also = ['pull', 'working-trees', 'status-flags']
1699
1378
    takes_args = ['dir?']
1700
 
    takes_options = ['revision',
1701
 
                     Option('show-base',
1702
 
                            help="Show base revision text in conflicts."),
1703
 
                     ]
 
1379
    takes_options = ['revision']
1704
1380
    aliases = ['up']
1705
1381
 
1706
 
    def run(self, dir=None, revision=None, show_base=None):
 
1382
    def run(self, dir='.', revision=None):
1707
1383
        if revision is not None and len(revision) != 1:
1708
 
            raise errors.BzrCommandError(gettext(
1709
 
                "bzr update --revision takes exactly one revision"))
1710
 
        if dir is None:
1711
 
            tree = WorkingTree.open_containing('.')[0]
1712
 
        else:
1713
 
            tree, relpath = WorkingTree.open_containing(dir)
1714
 
            if relpath:
1715
 
                # See bug 557886.
1716
 
                raise errors.BzrCommandError(gettext(
1717
 
                    "bzr update can only update a whole tree, "
1718
 
                    "not a file or subdirectory"))
 
1384
            raise errors.BzrCommandError(
 
1385
                        "bzr update --revision takes exactly one revision")
 
1386
        tree = WorkingTree.open_containing(dir)[0]
1719
1387
        branch = tree.branch
1720
1388
        possible_transports = []
1721
1389
        master = branch.get_master_branch(
1722
1390
            possible_transports=possible_transports)
1723
1391
        if master is not None:
 
1392
            tree.lock_write()
1724
1393
            branch_location = master.base
1725
 
            tree.lock_write()
1726
1394
        else:
 
1395
            tree.lock_tree_write()
1727
1396
            branch_location = tree.branch.base
1728
 
            tree.lock_tree_write()
1729
1397
        self.add_cleanup(tree.unlock)
1730
1398
        # get rid of the final '/' and be ready for display
1731
 
        branch_location = urlutils.unescape_for_display(
1732
 
            branch_location.rstrip('/'),
1733
 
            self.outf.encoding)
 
1399
        branch_location = urlutils.unescape_for_display(branch_location[:-1],
 
1400
                                                        self.outf.encoding)
1734
1401
        existing_pending_merges = tree.get_parent_ids()[1:]
1735
1402
        if master is None:
1736
1403
            old_tip = None
1744
1411
        else:
1745
1412
            revision_id = branch.last_revision()
1746
1413
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1747
 
            revno = branch.revision_id_to_dotted_revno(revision_id)
1748
 
            note(gettext("Tree is up to date at revision {0} of branch {1}"
1749
 
                        ).format('.'.join(map(str, revno)), branch_location))
 
1414
            revno = branch.revision_id_to_revno(revision_id)
 
1415
            note("Tree is up to date at revision %d of branch %s" %
 
1416
                (revno, branch_location))
1750
1417
            return 0
1751
1418
        view_info = _get_view_info_for_change_reporter(tree)
1752
1419
        change_reporter = delta._ChangeReporter(
1757
1424
                change_reporter,
1758
1425
                possible_transports=possible_transports,
1759
1426
                revision=revision_id,
1760
 
                old_tip=old_tip,
1761
 
                show_base=show_base)
 
1427
                old_tip=old_tip)
1762
1428
        except errors.NoSuchRevision, e:
1763
 
            raise errors.BzrCommandError(gettext(
 
1429
            raise errors.BzrCommandError(
1764
1430
                                  "branch has no revision %s\n"
1765
1431
                                  "bzr update --revision only works"
1766
 
                                  " for a revision in the branch history")
 
1432
                                  " for a revision in the branch history"
1767
1433
                                  % (e.revision))
1768
 
        revno = tree.branch.revision_id_to_dotted_revno(
 
1434
        revno = tree.branch.revision_id_to_revno(
1769
1435
            _mod_revision.ensure_null(tree.last_revision()))
1770
 
        note(gettext('Updated to revision {0} of branch {1}').format(
1771
 
             '.'.join(map(str, revno)), branch_location))
1772
 
        parent_ids = tree.get_parent_ids()
1773
 
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1774
 
            note(gettext('Your local commits will now show as pending merges with '
1775
 
                 "'bzr status', and can be committed with 'bzr commit'."))
 
1436
        note('Updated to revision %d of branch %s' %
 
1437
             (revno, branch_location))
 
1438
        if tree.get_parent_ids()[1:] != existing_pending_merges:
 
1439
            note('Your local commits will now show as pending merges with '
 
1440
                 "'bzr status', and can be committed with 'bzr commit'.")
1776
1441
        if conflicts != 0:
1777
1442
            return 1
1778
1443
        else:
1780
1445
 
1781
1446
 
1782
1447
class cmd_info(Command):
1783
 
    __doc__ = """Show information about a working tree, branch or repository.
 
1448
    """Show information about a working tree, branch or repository.
1784
1449
 
1785
1450
    This command will show all known locations and formats associated to the
1786
1451
    tree, branch or repository.
1819
1484
        else:
1820
1485
            noise_level = 0
1821
1486
        from bzrlib.info import show_bzrdir_info
1822
 
        show_bzrdir_info(controldir.ControlDir.open_containing(location)[0],
 
1487
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1823
1488
                         verbose=noise_level, outfile=self.outf)
1824
1489
 
1825
1490
 
1826
1491
class cmd_remove(Command):
1827
 
    __doc__ = """Remove files or directories.
 
1492
    """Remove files or directories.
1828
1493
 
1829
 
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1830
 
    delete them if they can easily be recovered using revert otherwise they
1831
 
    will be backed up (adding an extention of the form .~#~). If no options or
1832
 
    parameters are given Bazaar will scan for files that are being tracked by
1833
 
    Bazaar but missing in your tree and stop tracking them for you.
 
1494
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1495
    them if they can easily be recovered using revert. If no options or
 
1496
    parameters are given bzr will scan for files that are being tracked by bzr
 
1497
    but missing in your tree and stop tracking them for you.
1834
1498
    """
1835
1499
    takes_args = ['file*']
1836
1500
    takes_options = ['verbose',
1838
1502
        RegistryOption.from_kwargs('file-deletion-strategy',
1839
1503
            'The file deletion mode to be used.',
1840
1504
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1841
 
            safe='Backup changed files (default).',
 
1505
            safe='Only delete files if they can be'
 
1506
                 ' safely recovered (default).',
1842
1507
            keep='Delete from bzr but leave the working copy.',
1843
 
            no_backup='Don\'t backup changed files.',
1844
1508
            force='Delete all the specified files, even if they can not be '
1845
 
                'recovered and even if they are non-empty directories. '
1846
 
                '(deprecated, use no-backup)')]
 
1509
                'recovered and even if they are non-empty directories.')]
1847
1510
    aliases = ['rm', 'del']
1848
1511
    encoding_type = 'replace'
1849
1512
 
1850
1513
    def run(self, file_list, verbose=False, new=False,
1851
1514
        file_deletion_strategy='safe'):
1852
 
        if file_deletion_strategy == 'force':
1853
 
            note(gettext("(The --force option is deprecated, rather use --no-backup "
1854
 
                "in future.)"))
1855
 
            file_deletion_strategy = 'no-backup'
1856
 
 
1857
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1515
        tree, file_list = tree_files(file_list)
1858
1516
 
1859
1517
        if file_list is not None:
1860
1518
            file_list = [f for f in file_list]
1861
1519
 
1862
 
        self.add_cleanup(tree.lock_write().unlock)
 
1520
        tree.lock_write()
 
1521
        self.add_cleanup(tree.unlock)
1863
1522
        # Heuristics should probably all move into tree.remove_smart or
1864
1523
        # some such?
1865
1524
        if new:
1867
1526
                specific_files=file_list).added
1868
1527
            file_list = sorted([f[0] for f in added], reverse=True)
1869
1528
            if len(file_list) == 0:
1870
 
                raise errors.BzrCommandError(gettext('No matching files.'))
 
1529
                raise errors.BzrCommandError('No matching files.')
1871
1530
        elif file_list is None:
1872
1531
            # missing files show up in iter_changes(basis) as
1873
1532
            # versioned-with-no-kind.
1880
1539
            file_deletion_strategy = 'keep'
1881
1540
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1882
1541
            keep_files=file_deletion_strategy=='keep',
1883
 
            force=(file_deletion_strategy=='no-backup'))
 
1542
            force=file_deletion_strategy=='force')
1884
1543
 
1885
1544
 
1886
1545
class cmd_file_id(Command):
1887
 
    __doc__ = """Print file_id of a particular file or directory.
 
1546
    """Print file_id of a particular file or directory.
1888
1547
 
1889
1548
    The file_id is assigned when the file is first added and remains the
1890
1549
    same through all revisions where the file exists, even when it is
1906
1565
 
1907
1566
 
1908
1567
class cmd_file_path(Command):
1909
 
    __doc__ = """Print path of file_ids to a file or directory.
 
1568
    """Print path of file_ids to a file or directory.
1910
1569
 
1911
1570
    This prints one line for each directory down to the target,
1912
1571
    starting at the branch root.
1928
1587
 
1929
1588
 
1930
1589
class cmd_reconcile(Command):
1931
 
    __doc__ = """Reconcile bzr metadata in a branch.
 
1590
    """Reconcile bzr metadata in a branch.
1932
1591
 
1933
1592
    This can correct data mismatches that may have been caused by
1934
1593
    previous ghost operations or bzr upgrades. You should only
1948
1607
 
1949
1608
    _see_also = ['check']
1950
1609
    takes_args = ['branch?']
1951
 
    takes_options = [
1952
 
        Option('canonicalize-chks',
1953
 
               help='Make sure CHKs are in canonical form (repairs '
1954
 
                    'bug 522637).',
1955
 
               hidden=True),
1956
 
        ]
1957
1610
 
1958
 
    def run(self, branch=".", canonicalize_chks=False):
 
1611
    def run(self, branch="."):
1959
1612
        from bzrlib.reconcile import reconcile
1960
 
        dir = controldir.ControlDir.open(branch)
1961
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1613
        dir = bzrdir.BzrDir.open(branch)
 
1614
        reconcile(dir)
1962
1615
 
1963
1616
 
1964
1617
class cmd_revision_history(Command):
1965
 
    __doc__ = """Display the list of revision ids on a branch."""
 
1618
    """Display the list of revision ids on a branch."""
1966
1619
 
1967
1620
    _see_also = ['log']
1968
1621
    takes_args = ['location?']
1972
1625
    @display_command
1973
1626
    def run(self, location="."):
1974
1627
        branch = Branch.open_containing(location)[0]
1975
 
        self.add_cleanup(branch.lock_read().unlock)
1976
 
        graph = branch.repository.get_graph()
1977
 
        history = list(graph.iter_lefthand_ancestry(branch.last_revision(),
1978
 
            [_mod_revision.NULL_REVISION]))
1979
 
        for revid in reversed(history):
 
1628
        for revid in branch.revision_history():
1980
1629
            self.outf.write(revid)
1981
1630
            self.outf.write('\n')
1982
1631
 
1983
1632
 
1984
1633
class cmd_ancestry(Command):
1985
 
    __doc__ = """List all revisions merged into this branch."""
 
1634
    """List all revisions merged into this branch."""
1986
1635
 
1987
1636
    _see_also = ['log', 'revision-history']
1988
1637
    takes_args = ['location?']
2000
1649
            b = wt.branch
2001
1650
            last_revision = wt.last_revision()
2002
1651
 
2003
 
        self.add_cleanup(b.repository.lock_read().unlock)
2004
 
        graph = b.repository.get_graph()
2005
 
        revisions = [revid for revid, parents in
2006
 
            graph.iter_ancestry([last_revision])]
2007
 
        for revision_id in reversed(revisions):
2008
 
            if _mod_revision.is_null(revision_id):
2009
 
                continue
 
1652
        revision_ids = b.repository.get_ancestry(last_revision)
 
1653
        revision_ids.pop(0)
 
1654
        for revision_id in revision_ids:
2010
1655
            self.outf.write(revision_id + '\n')
2011
1656
 
2012
1657
 
2013
1658
class cmd_init(Command):
2014
 
    __doc__ = """Make a directory into a versioned branch.
 
1659
    """Make a directory into a versioned branch.
2015
1660
 
2016
1661
    Use this to create an empty branch, or before importing an
2017
1662
    existing project.
2043
1688
                help='Specify a format for this branch. '
2044
1689
                'See "help formats".',
2045
1690
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
2046
 
                converter=lambda name: controldir.format_registry.make_bzrdir(name),
 
1691
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2047
1692
                value_switches=True,
2048
1693
                title="Branch format",
2049
1694
                ),
2050
1695
         Option('append-revisions-only',
2051
1696
                help='Never change revnos or the existing log.'
2052
 
                '  Append revisions to it only.'),
2053
 
         Option('no-tree',
2054
 
                'Create a branch without a working tree.')
 
1697
                '  Append revisions to it only.')
2055
1698
         ]
2056
1699
    def run(self, location=None, format=None, append_revisions_only=False,
2057
 
            create_prefix=False, no_tree=False):
 
1700
            create_prefix=False):
2058
1701
        if format is None:
2059
 
            format = controldir.format_registry.make_bzrdir('default')
 
1702
            format = bzrdir.format_registry.make_bzrdir('default')
2060
1703
        if location is None:
2061
1704
            location = u'.'
2062
1705
 
2071
1714
            to_transport.ensure_base()
2072
1715
        except errors.NoSuchFile:
2073
1716
            if not create_prefix:
2074
 
                raise errors.BzrCommandError(gettext("Parent directory of %s"
 
1717
                raise errors.BzrCommandError("Parent directory of %s"
2075
1718
                    " does not exist."
2076
1719
                    "\nYou may supply --create-prefix to create all"
2077
 
                    " leading parent directories.")
 
1720
                    " leading parent directories."
2078
1721
                    % location)
2079
1722
            to_transport.create_prefix()
2080
1723
 
2081
1724
        try:
2082
 
            a_bzrdir = controldir.ControlDir.open_from_transport(to_transport)
 
1725
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
2083
1726
        except errors.NotBranchError:
2084
1727
            # really a NotBzrDir error...
2085
 
            create_branch = controldir.ControlDir.create_branch_convenience
2086
 
            if no_tree:
2087
 
                force_new_tree = False
2088
 
            else:
2089
 
                force_new_tree = None
 
1728
            create_branch = bzrdir.BzrDir.create_branch_convenience
2090
1729
            branch = create_branch(to_transport.base, format=format,
2091
 
                                   possible_transports=[to_transport],
2092
 
                                   force_new_tree=force_new_tree)
 
1730
                                   possible_transports=[to_transport])
2093
1731
            a_bzrdir = branch.bzrdir
2094
1732
        else:
2095
1733
            from bzrlib.transport.local import LocalTransport
2099
1737
                        raise errors.BranchExistsWithoutWorkingTree(location)
2100
1738
                raise errors.AlreadyBranchError(location)
2101
1739
            branch = a_bzrdir.create_branch()
2102
 
            if not no_tree and not a_bzrdir.has_workingtree():
2103
 
                a_bzrdir.create_workingtree()
 
1740
            a_bzrdir.create_workingtree()
2104
1741
        if append_revisions_only:
2105
1742
            try:
2106
1743
                branch.set_append_revisions_only(True)
2107
1744
            except errors.UpgradeRequired:
2108
 
                raise errors.BzrCommandError(gettext('This branch format cannot be set'
2109
 
                    ' to append-revisions-only.  Try --default.'))
 
1745
                raise errors.BzrCommandError('This branch format cannot be set'
 
1746
                    ' to append-revisions-only.  Try --default.')
2110
1747
        if not is_quiet():
2111
1748
            from bzrlib.info import describe_layout, describe_format
2112
1749
            try:
2116
1753
            repository = branch.repository
2117
1754
            layout = describe_layout(repository, branch, tree).lower()
2118
1755
            format = describe_format(a_bzrdir, repository, branch, tree)
2119
 
            self.outf.write(gettext("Created a {0} (format: {1})\n").format(
2120
 
                  layout, format))
 
1756
            self.outf.write("Created a %s (format: %s)\n" % (layout, format))
2121
1757
            if repository.is_shared():
2122
1758
                #XXX: maybe this can be refactored into transport.path_or_url()
2123
1759
                url = repository.bzrdir.root_transport.external_url()
2125
1761
                    url = urlutils.local_path_from_url(url)
2126
1762
                except errors.InvalidURL:
2127
1763
                    pass
2128
 
                self.outf.write(gettext("Using shared repository: %s\n") % url)
 
1764
                self.outf.write("Using shared repository: %s\n" % url)
2129
1765
 
2130
1766
 
2131
1767
class cmd_init_repository(Command):
2132
 
    __doc__ = """Create a shared repository for branches to share storage space.
 
1768
    """Create a shared repository for branches to share storage space.
2133
1769
 
2134
1770
    New branches created under the repository directory will store their
2135
1771
    revisions in the repository, not in the branch directory.  For branches
2161
1797
    takes_options = [RegistryOption('format',
2162
1798
                            help='Specify a format for this repository. See'
2163
1799
                                 ' "bzr help formats" for details.',
2164
 
                            lazy_registry=('bzrlib.controldir', 'format_registry'),
2165
 
                            converter=lambda name: controldir.format_registry.make_bzrdir(name),
 
1800
                            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1801
                            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2166
1802
                            value_switches=True, title='Repository format'),
2167
1803
                     Option('no-trees',
2168
1804
                             help='Branches in the repository will default to'
2172
1808
 
2173
1809
    def run(self, location, format=None, no_trees=False):
2174
1810
        if format is None:
2175
 
            format = controldir.format_registry.make_bzrdir('default')
 
1811
            format = bzrdir.format_registry.make_bzrdir('default')
2176
1812
 
2177
1813
        if location is None:
2178
1814
            location = '.'
2179
1815
 
2180
1816
        to_transport = transport.get_transport(location)
 
1817
        to_transport.ensure_base()
2181
1818
 
2182
 
        (repo, newdir, require_stacking, repository_policy) = (
2183
 
            format.initialize_on_transport_ex(to_transport,
2184
 
            create_prefix=True, make_working_trees=not no_trees,
2185
 
            shared_repo=True, force_new_repo=True,
2186
 
            use_existing_dir=True,
2187
 
            repo_format_name=format.repository_format.get_format_string()))
 
1819
        newdir = format.initialize_on_transport(to_transport)
 
1820
        repo = newdir.create_repository(shared=True)
 
1821
        repo.set_make_working_trees(not no_trees)
2188
1822
        if not is_quiet():
2189
1823
            from bzrlib.info import show_bzrdir_info
2190
 
            show_bzrdir_info(newdir, verbose=0, outfile=self.outf)
 
1824
            show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
2191
1825
 
2192
1826
 
2193
1827
class cmd_diff(Command):
2194
 
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1828
    """Show differences in the working tree, between revisions or branches.
2195
1829
 
2196
1830
    If no arguments are given, all changes for the current tree are listed.
2197
1831
    If files are given, only the changes in those files are listed.
2203
1837
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
2204
1838
    produces patches suitable for "patch -p1".
2205
1839
 
2206
 
    Note that when using the -r argument with a range of revisions, the
2207
 
    differences are computed between the two specified revisions.  That
2208
 
    is, the command does not show the changes introduced by the first 
2209
 
    revision in the range.  This differs from the interpretation of 
2210
 
    revision ranges used by "bzr log" which includes the first revision
2211
 
    in the range.
2212
 
 
2213
1840
    :Exit values:
2214
1841
        1 - changed
2215
1842
        2 - unrepresentable changes
2233
1860
 
2234
1861
            bzr diff -r1..3 xxx
2235
1862
 
2236
 
        The changes introduced by revision 2 (equivalent to -r1..2)::
2237
 
 
2238
 
            bzr diff -c2
2239
 
 
2240
 
        To see the changes introduced by revision X::
 
1863
        To see the changes introduced in revision X::
2241
1864
        
2242
1865
            bzr diff -cX
2243
1866
 
2247
1870
 
2248
1871
            bzr diff -r<chosen_parent>..X
2249
1872
 
2250
 
        The changes between the current revision and the previous revision
2251
 
        (equivalent to -c-1 and -r-2..-1)
 
1873
        The changes introduced by revision 2 (equivalent to -r1..2)::
2252
1874
 
2253
 
            bzr diff -r-2..
 
1875
            bzr diff -c2
2254
1876
 
2255
1877
        Show just the differences for file NEWS::
2256
1878
 
2271
1893
        Same as 'bzr diff' but prefix paths with old/ and new/::
2272
1894
 
2273
1895
            bzr diff --prefix old/:new/
2274
 
            
2275
 
        Show the differences using a custom diff program with options::
2276
 
        
2277
 
            bzr diff --using /usr/bin/diff --diff-options -wu
2278
1896
    """
2279
1897
    _see_also = ['status']
2280
1898
    takes_args = ['file*']
2299
1917
            help='Use this command to compare files.',
2300
1918
            type=unicode,
2301
1919
            ),
2302
 
        RegistryOption('format',
2303
 
            short_name='F',
2304
 
            help='Diff format to use.',
2305
 
            lazy_registry=('bzrlib.diff', 'format_registry'),
2306
 
            title='Diff format'),
2307
1920
        ]
2308
1921
    aliases = ['di', 'dif']
2309
1922
    encoding_type = 'exact'
2310
1923
 
2311
1924
    @display_command
2312
1925
    def run(self, revision=None, file_list=None, diff_options=None,
2313
 
            prefix=None, old=None, new=None, using=None, format=None):
2314
 
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
2315
 
            show_diff_trees)
 
1926
            prefix=None, old=None, new=None, using=None):
 
1927
        from bzrlib.diff import get_trees_and_branches_to_diff, show_diff_trees
2316
1928
 
2317
1929
        if (prefix is None) or (prefix == '0'):
2318
1930
            # diff -p0 format
2324
1936
        elif ':' in prefix:
2325
1937
            old_label, new_label = prefix.split(":")
2326
1938
        else:
2327
 
            raise errors.BzrCommandError(gettext(
 
1939
            raise errors.BzrCommandError(
2328
1940
                '--prefix expects two values separated by a colon'
2329
 
                ' (eg "old/:new/")'))
 
1941
                ' (eg "old/:new/")')
2330
1942
 
2331
1943
        if revision and len(revision) > 2:
2332
 
            raise errors.BzrCommandError(gettext('bzr diff --revision takes exactly'
2333
 
                                         ' one or two revision specifiers'))
2334
 
 
2335
 
        if using is not None and format is not None:
2336
 
            raise errors.BzrCommandError(gettext(
2337
 
                '{0} and {1} are mutually exclusive').format(
2338
 
                '--using', '--format'))
 
1944
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
 
1945
                                         ' one or two revision specifiers')
2339
1946
 
2340
1947
        (old_tree, new_tree,
2341
1948
         old_branch, new_branch,
2342
 
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
2343
 
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
2344
 
        # GNU diff on Windows uses ANSI encoding for filenames
2345
 
        path_encoding = osutils.get_diff_header_encoding()
 
1949
         specific_files, extra_trees) = get_trees_and_branches_to_diff(
 
1950
            file_list, revision, old, new, apply_view=True)
2346
1951
        return show_diff_trees(old_tree, new_tree, sys.stdout,
2347
1952
                               specific_files=specific_files,
2348
1953
                               external_diff_options=diff_options,
2349
1954
                               old_label=old_label, new_label=new_label,
2350
 
                               extra_trees=extra_trees,
2351
 
                               path_encoding=path_encoding,
2352
 
                               using=using,
2353
 
                               format_cls=format)
 
1955
                               extra_trees=extra_trees, using=using)
2354
1956
 
2355
1957
 
2356
1958
class cmd_deleted(Command):
2357
 
    __doc__ = """List files deleted in the working tree.
 
1959
    """List files deleted in the working tree.
2358
1960
    """
2359
1961
    # TODO: Show files deleted since a previous revision, or
2360
1962
    # between two revisions.
2363
1965
    # level of effort but possibly much less IO.  (Or possibly not,
2364
1966
    # if the directories are very large...)
2365
1967
    _see_also = ['status', 'ls']
2366
 
    takes_options = ['directory', 'show-ids']
 
1968
    takes_options = ['show-ids']
2367
1969
 
2368
1970
    @display_command
2369
 
    def run(self, show_ids=False, directory=u'.'):
2370
 
        tree = WorkingTree.open_containing(directory)[0]
2371
 
        self.add_cleanup(tree.lock_read().unlock)
 
1971
    def run(self, show_ids=False):
 
1972
        tree = WorkingTree.open_containing(u'.')[0]
 
1973
        tree.lock_read()
 
1974
        self.add_cleanup(tree.unlock)
2372
1975
        old = tree.basis_tree()
2373
 
        self.add_cleanup(old.lock_read().unlock)
2374
 
        for path, ie in old.iter_entries_by_dir():
 
1976
        old.lock_read()
 
1977
        self.add_cleanup(old.unlock)
 
1978
        for path, ie in old.inventory.iter_entries():
2375
1979
            if not tree.has_id(ie.file_id):
2376
1980
                self.outf.write(path)
2377
1981
                if show_ids:
2381
1985
 
2382
1986
 
2383
1987
class cmd_modified(Command):
2384
 
    __doc__ = """List files modified in working tree.
 
1988
    """List files modified in working tree.
2385
1989
    """
2386
1990
 
2387
1991
    hidden = True
2388
1992
    _see_also = ['status', 'ls']
2389
 
    takes_options = ['directory', 'null']
 
1993
    takes_options = [
 
1994
            Option('null',
 
1995
                   help='Write an ascii NUL (\\0) separator '
 
1996
                   'between files rather than a newline.')
 
1997
            ]
2390
1998
 
2391
1999
    @display_command
2392
 
    def run(self, null=False, directory=u'.'):
2393
 
        tree = WorkingTree.open_containing(directory)[0]
2394
 
        self.add_cleanup(tree.lock_read().unlock)
 
2000
    def run(self, null=False):
 
2001
        tree = WorkingTree.open_containing(u'.')[0]
2395
2002
        td = tree.changes_from(tree.basis_tree())
2396
 
        self.cleanup_now()
2397
2003
        for path, id, kind, text_modified, meta_modified in td.modified:
2398
2004
            if null:
2399
2005
                self.outf.write(path + '\0')
2402
2008
 
2403
2009
 
2404
2010
class cmd_added(Command):
2405
 
    __doc__ = """List files added in working tree.
 
2011
    """List files added in working tree.
2406
2012
    """
2407
2013
 
2408
2014
    hidden = True
2409
2015
    _see_also = ['status', 'ls']
2410
 
    takes_options = ['directory', 'null']
 
2016
    takes_options = [
 
2017
            Option('null',
 
2018
                   help='Write an ascii NUL (\\0) separator '
 
2019
                   'between files rather than a newline.')
 
2020
            ]
2411
2021
 
2412
2022
    @display_command
2413
 
    def run(self, null=False, directory=u'.'):
2414
 
        wt = WorkingTree.open_containing(directory)[0]
2415
 
        self.add_cleanup(wt.lock_read().unlock)
 
2023
    def run(self, null=False):
 
2024
        wt = WorkingTree.open_containing(u'.')[0]
 
2025
        wt.lock_read()
 
2026
        self.add_cleanup(wt.unlock)
2416
2027
        basis = wt.basis_tree()
2417
 
        self.add_cleanup(basis.lock_read().unlock)
2418
 
        root_id = wt.get_root_id()
2419
 
        for file_id in wt.all_file_ids():
2420
 
            if basis.has_id(file_id):
2421
 
                continue
2422
 
            if root_id == file_id:
2423
 
                continue
2424
 
            path = wt.id2path(file_id)
2425
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
 
2028
        basis.lock_read()
 
2029
        self.add_cleanup(basis.unlock)
 
2030
        basis_inv = basis.inventory
 
2031
        inv = wt.inventory
 
2032
        for file_id in inv:
 
2033
            if file_id in basis_inv:
 
2034
                continue
 
2035
            if inv.is_root(file_id) and len(basis_inv) == 0:
 
2036
                continue
 
2037
            path = inv.id2path(file_id)
 
2038
            if not os.access(osutils.abspath(path), os.F_OK):
2426
2039
                continue
2427
2040
            if null:
2428
2041
                self.outf.write(path + '\0')
2431
2044
 
2432
2045
 
2433
2046
class cmd_root(Command):
2434
 
    __doc__ = """Show the tree root directory.
 
2047
    """Show the tree root directory.
2435
2048
 
2436
2049
    The root is the nearest enclosing directory with a .bzr control
2437
2050
    directory."""
2448
2061
    try:
2449
2062
        return int(limitstring)
2450
2063
    except ValueError:
2451
 
        msg = gettext("The limit argument must be an integer.")
 
2064
        msg = "The limit argument must be an integer."
2452
2065
        raise errors.BzrCommandError(msg)
2453
2066
 
2454
2067
 
2456
2069
    try:
2457
2070
        return int(s)
2458
2071
    except ValueError:
2459
 
        msg = gettext("The levels argument must be an integer.")
 
2072
        msg = "The levels argument must be an integer."
2460
2073
        raise errors.BzrCommandError(msg)
2461
2074
 
2462
2075
 
2463
2076
class cmd_log(Command):
2464
 
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2077
    """Show historical log for a branch or subset of a branch.
2465
2078
 
2466
2079
    log is bzr's default tool for exploring the history of a branch.
2467
2080
    The branch to use is taken from the first parameter. If no parameters
2572
2185
 
2573
2186
    :Other filtering:
2574
2187
 
2575
 
      The --match option can be used for finding revisions that match a
2576
 
      regular expression in a commit message, committer, author or bug.
2577
 
      Specifying the option several times will match any of the supplied
2578
 
      expressions. --match-author, --match-bugs, --match-committer and
2579
 
      --match-message can be used to only match a specific field.
 
2188
      The --message option can be used for finding revisions that match a
 
2189
      regular expression in a commit message.
2580
2190
 
2581
2191
    :Tips & tricks:
2582
2192
 
2631
2241
                   help='Show just the specified revision.'
2632
2242
                   ' See also "help revisionspec".'),
2633
2243
            'log-format',
2634
 
            RegistryOption('authors',
2635
 
                'What names to list as authors - first, all or committer.',
2636
 
                title='Authors',
2637
 
                lazy_registry=('bzrlib.log', 'author_list_registry'),
2638
 
            ),
2639
2244
            Option('levels',
2640
2245
                   short_name='n',
2641
2246
                   help='Number of levels to display - 0 for all, 1 for flat.',
2642
2247
                   argname='N',
2643
2248
                   type=_parse_levels),
2644
2249
            Option('message',
 
2250
                   short_name='m',
2645
2251
                   help='Show revisions whose message matches this '
2646
2252
                        'regular expression.',
2647
 
                   type=str,
2648
 
                   hidden=True),
 
2253
                   type=str),
2649
2254
            Option('limit',
2650
2255
                   short_name='l',
2651
2256
                   help='Limit the output to the first N revisions.',
2654
2259
            Option('show-diff',
2655
2260
                   short_name='p',
2656
2261
                   help='Show changes made in each revision as a patch.'),
2657
 
            Option('include-merged',
 
2262
            Option('include-merges',
2658
2263
                   help='Show merged revisions like --levels 0 does.'),
2659
 
            Option('include-merges', hidden=True,
2660
 
                   help='Historical alias for --include-merged.'),
2661
 
            Option('omit-merges',
2662
 
                   help='Do not report commits with more than one parent.'),
2663
 
            Option('exclude-common-ancestry',
2664
 
                   help='Display only the revisions that are not part'
2665
 
                   ' of both ancestries (require -rX..Y).'
2666
 
                   ),
2667
 
            Option('signatures',
2668
 
                   help='Show digital signature validity.'),
2669
 
            ListOption('match',
2670
 
                short_name='m',
2671
 
                help='Show revisions whose properties match this '
2672
 
                'expression.',
2673
 
                type=str),
2674
 
            ListOption('match-message',
2675
 
                   help='Show revisions whose message matches this '
2676
 
                   'expression.',
2677
 
                type=str),
2678
 
            ListOption('match-committer',
2679
 
                   help='Show revisions whose committer matches this '
2680
 
                   'expression.',
2681
 
                type=str),
2682
 
            ListOption('match-author',
2683
 
                   help='Show revisions whose authors match this '
2684
 
                   'expression.',
2685
 
                type=str),
2686
 
            ListOption('match-bugs',
2687
 
                   help='Show revisions whose bugs match this '
2688
 
                   'expression.',
2689
 
                type=str)
2690
2264
            ]
2691
2265
    encoding_type = 'replace'
2692
2266
 
2702
2276
            message=None,
2703
2277
            limit=None,
2704
2278
            show_diff=False,
2705
 
            include_merged=None,
2706
 
            authors=None,
2707
 
            exclude_common_ancestry=False,
2708
 
            signatures=False,
2709
 
            match=None,
2710
 
            match_message=None,
2711
 
            match_committer=None,
2712
 
            match_author=None,
2713
 
            match_bugs=None,
2714
 
            omit_merges=False,
2715
 
            include_merges=symbol_versioning.DEPRECATED_PARAMETER,
2716
 
            ):
 
2279
            include_merges=False):
2717
2280
        from bzrlib.log import (
2718
2281
            Logger,
2719
2282
            make_log_request_dict,
2720
2283
            _get_info_for_log_files,
2721
2284
            )
2722
2285
        direction = (forward and 'forward') or 'reverse'
2723
 
        if symbol_versioning.deprecated_passed(include_merges):
2724
 
            ui.ui_factory.show_user_warning(
2725
 
                'deprecated_command_option',
2726
 
                deprecated_name='--include-merges',
2727
 
                recommended_name='--include-merged',
2728
 
                deprecated_in_version='2.5',
2729
 
                command=self.invoked_as)
2730
 
            if include_merged is None:
2731
 
                include_merged = include_merges
2732
 
            else:
2733
 
                raise errors.BzrCommandError(gettext(
2734
 
                    '{0} and {1} are mutually exclusive').format(
2735
 
                    '--include-merges', '--include-merged'))
2736
 
        if include_merged is None:
2737
 
            include_merged = False
2738
 
        if (exclude_common_ancestry
2739
 
            and (revision is None or len(revision) != 2)):
2740
 
            raise errors.BzrCommandError(gettext(
2741
 
                '--exclude-common-ancestry requires -r with two revisions'))
2742
 
        if include_merged:
 
2286
        if include_merges:
2743
2287
            if levels is None:
2744
2288
                levels = 0
2745
2289
            else:
2746
 
                raise errors.BzrCommandError(gettext(
2747
 
                    '{0} and {1} are mutually exclusive').format(
2748
 
                    '--levels', '--include-merged'))
 
2290
                raise errors.BzrCommandError(
 
2291
                    '--levels and --include-merges are mutually exclusive')
2749
2292
 
2750
2293
        if change is not None:
2751
2294
            if len(change) > 1:
2752
2295
                raise errors.RangeInChangeOption()
2753
2296
            if revision is not None:
2754
 
                raise errors.BzrCommandError(gettext(
2755
 
                    '{0} and {1} are mutually exclusive').format(
2756
 
                    '--revision', '--change'))
 
2297
                raise errors.BzrCommandError(
 
2298
                    '--revision and --change are mutually exclusive')
2757
2299
            else:
2758
2300
                revision = change
2759
2301
 
2762
2304
        if file_list:
2763
2305
            # find the file ids to log and check for directory filtering
2764
2306
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2765
 
                revision, file_list, self.add_cleanup)
 
2307
                revision, file_list)
 
2308
            self.add_cleanup(b.unlock)
2766
2309
            for relpath, file_id, kind in file_info_list:
2767
2310
                if file_id is None:
2768
 
                    raise errors.BzrCommandError(gettext(
2769
 
                        "Path unknown at end or start of revision range: %s") %
 
2311
                    raise errors.BzrCommandError(
 
2312
                        "Path unknown at end or start of revision range: %s" %
2770
2313
                        relpath)
2771
2314
                # If the relpath is the top of the tree, we log everything
2772
2315
                if relpath == '':
2784
2327
                location = revision[0].get_branch()
2785
2328
            else:
2786
2329
                location = '.'
2787
 
            dir, relpath = controldir.ControlDir.open_containing(location)
 
2330
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2788
2331
            b = dir.open_branch()
2789
 
            self.add_cleanup(b.lock_read().unlock)
 
2332
            b.lock_read()
 
2333
            self.add_cleanup(b.unlock)
2790
2334
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2791
2335
 
2792
 
        if b.get_config_stack().get('validate_signatures_in_log'):
2793
 
            signatures = True
2794
 
 
2795
 
        if signatures:
2796
 
            if not gpg.GPGStrategy.verify_signatures_available():
2797
 
                raise errors.GpgmeNotInstalled(None)
2798
 
 
2799
2336
        # Decide on the type of delta & diff filtering to use
2800
2337
        # TODO: add an --all-files option to make this configurable & consistent
2801
2338
        if not verbose:
2819
2356
                        show_timezone=timezone,
2820
2357
                        delta_format=get_verbosity_level(),
2821
2358
                        levels=levels,
2822
 
                        show_advice=levels is None,
2823
 
                        author_list_handler=authors)
 
2359
                        show_advice=levels is None)
2824
2360
 
2825
2361
        # Choose the algorithm for doing the logging. It's annoying
2826
2362
        # having multiple code paths like this but necessary until
2838
2374
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2839
2375
            or delta_type or partial_history)
2840
2376
 
2841
 
        match_dict = {}
2842
 
        if match:
2843
 
            match_dict[''] = match
2844
 
        if match_message:
2845
 
            match_dict['message'] = match_message
2846
 
        if match_committer:
2847
 
            match_dict['committer'] = match_committer
2848
 
        if match_author:
2849
 
            match_dict['author'] = match_author
2850
 
        if match_bugs:
2851
 
            match_dict['bugs'] = match_bugs
2852
 
 
2853
2377
        # Build the LogRequest and execute it
2854
2378
        if len(file_ids) == 0:
2855
2379
            file_ids = None
2857
2381
            direction=direction, specific_fileids=file_ids,
2858
2382
            start_revision=rev1, end_revision=rev2, limit=limit,
2859
2383
            message_search=message, delta_type=delta_type,
2860
 
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2861
 
            exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
2862
 
            signature=signatures, omit_merges=omit_merges,
2863
 
            )
 
2384
            diff_type=diff_type, _match_using_deltas=match_using_deltas)
2864
2385
        Logger(b, rqst).show(lf)
2865
2386
 
2866
2387
 
2882
2403
            # b is taken from revision[0].get_branch(), and
2883
2404
            # show_log will use its revision_history. Having
2884
2405
            # different branches will lead to weird behaviors.
2885
 
            raise errors.BzrCommandError(gettext(
 
2406
            raise errors.BzrCommandError(
2886
2407
                "bzr %s doesn't accept two revisions in different"
2887
 
                " branches.") % command_name)
2888
 
        if start_spec.spec is None:
2889
 
            # Avoid loading all the history.
2890
 
            rev1 = RevisionInfo(branch, None, None)
2891
 
        else:
2892
 
            rev1 = start_spec.in_history(branch)
 
2408
                " branches." % command_name)
 
2409
        rev1 = start_spec.in_history(branch)
2893
2410
        # Avoid loading all of history when we know a missing
2894
2411
        # end of range means the last revision ...
2895
2412
        if end_spec.spec is None:
2898
2415
        else:
2899
2416
            rev2 = end_spec.in_history(branch)
2900
2417
    else:
2901
 
        raise errors.BzrCommandError(gettext(
2902
 
            'bzr %s --revision takes one or two values.') % command_name)
 
2418
        raise errors.BzrCommandError(
 
2419
            'bzr %s --revision takes one or two values.' % command_name)
2903
2420
    return rev1, rev2
2904
2421
 
2905
2422
 
2924
2441
 
2925
2442
 
2926
2443
class cmd_touching_revisions(Command):
2927
 
    __doc__ = """Return revision-ids which affected a particular file.
 
2444
    """Return revision-ids which affected a particular file.
2928
2445
 
2929
2446
    A more user-friendly interface is "bzr log FILE".
2930
2447
    """
2937
2454
        tree, relpath = WorkingTree.open_containing(filename)
2938
2455
        file_id = tree.path2id(relpath)
2939
2456
        b = tree.branch
2940
 
        self.add_cleanup(b.lock_read().unlock)
 
2457
        b.lock_read()
 
2458
        self.add_cleanup(b.unlock)
2941
2459
        touching_revs = log.find_touching_revisions(b, file_id)
2942
2460
        for revno, revision_id, what in touching_revs:
2943
2461
            self.outf.write("%6d %s\n" % (revno, what))
2944
2462
 
2945
2463
 
2946
2464
class cmd_ls(Command):
2947
 
    __doc__ = """List files in a tree.
 
2465
    """List files in a tree.
2948
2466
    """
2949
2467
 
2950
2468
    _see_also = ['status', 'cat']
2956
2474
                   help='Recurse into subdirectories.'),
2957
2475
            Option('from-root',
2958
2476
                   help='Print paths relative to the root of the branch.'),
2959
 
            Option('unknown', short_name='u',
2960
 
                help='Print unknown files.'),
 
2477
            Option('unknown', help='Print unknown files.'),
2961
2478
            Option('versioned', help='Print versioned files.',
2962
2479
                   short_name='V'),
2963
 
            Option('ignored', short_name='i',
2964
 
                help='Print ignored files.'),
2965
 
            Option('kind', short_name='k',
 
2480
            Option('ignored', help='Print ignored files.'),
 
2481
            Option('null',
 
2482
                   help='Write an ascii NUL (\\0) separator '
 
2483
                   'between files rather than a newline.'),
 
2484
            Option('kind',
2966
2485
                   help='List entries of a particular kind: file, directory, symlink.',
2967
2486
                   type=unicode),
2968
 
            'null',
2969
2487
            'show-ids',
2970
 
            'directory',
2971
2488
            ]
2972
2489
    @display_command
2973
2490
    def run(self, revision=None, verbose=False,
2974
2491
            recursive=False, from_root=False,
2975
2492
            unknown=False, versioned=False, ignored=False,
2976
 
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2493
            null=False, kind=None, show_ids=False, path=None):
2977
2494
 
2978
2495
        if kind and kind not in ('file', 'directory', 'symlink'):
2979
 
            raise errors.BzrCommandError(gettext('invalid kind specified'))
 
2496
            raise errors.BzrCommandError('invalid kind specified')
2980
2497
 
2981
2498
        if verbose and null:
2982
 
            raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
 
2499
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
2983
2500
        all = not (unknown or versioned or ignored)
2984
2501
 
2985
2502
        selection = {'I':ignored, '?':unknown, 'V':versioned}
2988
2505
            fs_path = '.'
2989
2506
        else:
2990
2507
            if from_root:
2991
 
                raise errors.BzrCommandError(gettext('cannot specify both --from-root'
2992
 
                                             ' and PATH'))
 
2508
                raise errors.BzrCommandError('cannot specify both --from-root'
 
2509
                                             ' and PATH')
2993
2510
            fs_path = path
2994
 
        tree, branch, relpath = \
2995
 
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2511
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2512
            fs_path)
2996
2513
 
2997
2514
        # Calculate the prefix to use
2998
2515
        prefix = None
3011
2528
            if view_files:
3012
2529
                apply_view = True
3013
2530
                view_str = views.view_display_str(view_files)
3014
 
                note(gettext("Ignoring files outside view. View is %s") % view_str)
 
2531
                note("Ignoring files outside view. View is %s" % view_str)
3015
2532
 
3016
 
        self.add_cleanup(tree.lock_read().unlock)
 
2533
        tree.lock_read()
 
2534
        self.add_cleanup(tree.unlock)
3017
2535
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
3018
2536
            from_dir=relpath, recursive=recursive):
3019
2537
            # Apply additional masking
3061
2579
 
3062
2580
 
3063
2581
class cmd_unknowns(Command):
3064
 
    __doc__ = """List unknown files.
 
2582
    """List unknown files.
3065
2583
    """
3066
2584
 
3067
2585
    hidden = True
3068
2586
    _see_also = ['ls']
3069
 
    takes_options = ['directory']
3070
2587
 
3071
2588
    @display_command
3072
 
    def run(self, directory=u'.'):
3073
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
2589
    def run(self):
 
2590
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
3074
2591
            self.outf.write(osutils.quotefn(f) + '\n')
3075
2592
 
3076
2593
 
3077
2594
class cmd_ignore(Command):
3078
 
    __doc__ = """Ignore specified files or patterns.
 
2595
    """Ignore specified files or patterns.
3079
2596
 
3080
2597
    See ``bzr help patterns`` for details on the syntax of patterns.
3081
2598
 
3090
2607
    using this command or directly by using an editor, be sure to commit
3091
2608
    it.
3092
2609
    
3093
 
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
3094
 
    the global ignore file can be found in the application data directory as
3095
 
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
3096
 
    Global ignores are not touched by this command. The global ignore file
3097
 
    can be edited directly using an editor.
3098
 
 
3099
2610
    Patterns prefixed with '!' are exceptions to ignore patterns and take
3100
2611
    precedence over regular ignores.  Such exceptions are used to specify
3101
2612
    files that should be versioned which would otherwise be ignored.
3103
2614
    Patterns prefixed with '!!' act as regular ignore patterns, but have
3104
2615
    precedence over the '!' exception patterns.
3105
2616
 
3106
 
    :Notes: 
3107
 
        
3108
 
    * Ignore patterns containing shell wildcards must be quoted from
3109
 
      the shell on Unix.
3110
 
 
3111
 
    * Ignore patterns starting with "#" act as comments in the ignore file.
3112
 
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
2617
    Note: ignore patterns containing shell wildcards must be quoted from
 
2618
    the shell on Unix.
3113
2619
 
3114
2620
    :Examples:
3115
2621
        Ignore the top level Makefile::
3124
2630
 
3125
2631
            bzr ignore "!special.class"
3126
2632
 
3127
 
        Ignore files whose name begins with the "#" character::
3128
 
 
3129
 
            bzr ignore "RE:^#"
3130
 
 
3131
2633
        Ignore .o files under the lib directory::
3132
2634
 
3133
2635
            bzr ignore "lib/**/*.o"
3141
2643
            bzr ignore "RE:(?!debian/).*"
3142
2644
        
3143
2645
        Ignore everything except the "local" toplevel directory,
3144
 
        but always ignore autosave files ending in ~, even under local/::
 
2646
        but always ignore "*~" autosave files, even under local/::
3145
2647
        
3146
2648
            bzr ignore "*"
3147
2649
            bzr ignore "!./local"
3150
2652
 
3151
2653
    _see_also = ['status', 'ignored', 'patterns']
3152
2654
    takes_args = ['name_pattern*']
3153
 
    takes_options = ['directory',
3154
 
        Option('default-rules',
3155
 
               help='Display the default ignore rules that bzr uses.')
 
2655
    takes_options = [
 
2656
        Option('old-default-rules',
 
2657
               help='Write out the ignore rules bzr < 0.9 always used.')
3156
2658
        ]
3157
2659
 
3158
 
    def run(self, name_pattern_list=None, default_rules=None,
3159
 
            directory=u'.'):
 
2660
    def run(self, name_pattern_list=None, old_default_rules=None):
3160
2661
        from bzrlib import ignores
3161
 
        if default_rules is not None:
3162
 
            # dump the default rules and exit
3163
 
            for pattern in ignores.USER_DEFAULTS:
3164
 
                self.outf.write("%s\n" % pattern)
 
2662
        if old_default_rules is not None:
 
2663
            # dump the rules and exit
 
2664
            for pattern in ignores.OLD_DEFAULTS:
 
2665
                print pattern
3165
2666
            return
3166
2667
        if not name_pattern_list:
3167
 
            raise errors.BzrCommandError(gettext("ignore requires at least one "
3168
 
                "NAME_PATTERN or --default-rules."))
 
2668
            raise errors.BzrCommandError("ignore requires at least one "
 
2669
                                  "NAME_PATTERN or --old-default-rules")
3169
2670
        name_pattern_list = [globbing.normalize_pattern(p)
3170
2671
                             for p in name_pattern_list]
3171
 
        bad_patterns = ''
3172
 
        bad_patterns_count = 0
3173
 
        for p in name_pattern_list:
3174
 
            if not globbing.Globster.is_pattern_valid(p):
3175
 
                bad_patterns_count += 1
3176
 
                bad_patterns += ('\n  %s' % p)
3177
 
        if bad_patterns:
3178
 
            msg = (ngettext('Invalid ignore pattern found. %s', 
3179
 
                            'Invalid ignore patterns found. %s',
3180
 
                            bad_patterns_count) % bad_patterns)
3181
 
            ui.ui_factory.show_error(msg)
3182
 
            raise errors.InvalidPattern('')
3183
2672
        for name_pattern in name_pattern_list:
3184
2673
            if (name_pattern[0] == '/' or
3185
2674
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
3186
 
                raise errors.BzrCommandError(gettext(
3187
 
                    "NAME_PATTERN should not be an absolute path"))
3188
 
        tree, relpath = WorkingTree.open_containing(directory)
 
2675
                raise errors.BzrCommandError(
 
2676
                    "NAME_PATTERN should not be an absolute path")
 
2677
        tree, relpath = WorkingTree.open_containing(u'.')
3189
2678
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
3190
2679
        ignored = globbing.Globster(name_pattern_list)
3191
2680
        matches = []
3192
 
        self.add_cleanup(tree.lock_read().unlock)
 
2681
        tree.lock_read()
3193
2682
        for entry in tree.list_files():
3194
2683
            id = entry[3]
3195
2684
            if id is not None:
3196
2685
                filename = entry[0]
3197
2686
                if ignored.match(filename):
3198
 
                    matches.append(filename)
 
2687
                    matches.append(filename.encode('utf-8'))
 
2688
        tree.unlock()
3199
2689
        if len(matches) > 0:
3200
 
            self.outf.write(gettext("Warning: the following files are version "
3201
 
                  "controlled and match your ignore pattern:\n%s"
3202
 
                  "\nThese files will continue to be version controlled"
3203
 
                  " unless you 'bzr remove' them.\n") % ("\n".join(matches),))
 
2690
            print "Warning: the following files are version controlled and" \
 
2691
                  " match your ignore pattern:\n%s" \
 
2692
                  "\nThese files will continue to be version controlled" \
 
2693
                  " unless you 'bzr remove' them." % ("\n".join(matches),)
3204
2694
 
3205
2695
 
3206
2696
class cmd_ignored(Command):
3207
 
    __doc__ = """List ignored files and the patterns that matched them.
 
2697
    """List ignored files and the patterns that matched them.
3208
2698
 
3209
2699
    List all the ignored files and the ignore pattern that caused the file to
3210
2700
    be ignored.
3216
2706
 
3217
2707
    encoding_type = 'replace'
3218
2708
    _see_also = ['ignore', 'ls']
3219
 
    takes_options = ['directory']
3220
2709
 
3221
2710
    @display_command
3222
 
    def run(self, directory=u'.'):
3223
 
        tree = WorkingTree.open_containing(directory)[0]
3224
 
        self.add_cleanup(tree.lock_read().unlock)
 
2711
    def run(self):
 
2712
        tree = WorkingTree.open_containing(u'.')[0]
 
2713
        tree.lock_read()
 
2714
        self.add_cleanup(tree.unlock)
3225
2715
        for path, file_class, kind, file_id, entry in tree.list_files():
3226
2716
            if file_class != 'I':
3227
2717
                continue
3231
2721
 
3232
2722
 
3233
2723
class cmd_lookup_revision(Command):
3234
 
    __doc__ = """Lookup the revision-id from a revision-number
 
2724
    """Lookup the revision-id from a revision-number
3235
2725
 
3236
2726
    :Examples:
3237
2727
        bzr lookup-revision 33
3238
2728
    """
3239
2729
    hidden = True
3240
2730
    takes_args = ['revno']
3241
 
    takes_options = ['directory']
3242
2731
 
3243
2732
    @display_command
3244
 
    def run(self, revno, directory=u'.'):
 
2733
    def run(self, revno):
3245
2734
        try:
3246
2735
            revno = int(revno)
3247
2736
        except ValueError:
3248
 
            raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
3249
 
                                         % revno)
3250
 
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
3251
 
        self.outf.write("%s\n" % revid)
 
2737
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
 
2738
 
 
2739
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
3252
2740
 
3253
2741
 
3254
2742
class cmd_export(Command):
3255
 
    __doc__ = """Export current or past revision to a destination directory or archive.
 
2743
    """Export current or past revision to a destination directory or archive.
3256
2744
 
3257
2745
    If no revision is specified this exports the last committed revision.
3258
2746
 
3279
2767
         zip                          .zip
3280
2768
      =================       =========================
3281
2769
    """
3282
 
    encoding = 'exact'
3283
2770
    takes_args = ['dest', 'branch_or_subdir?']
3284
 
    takes_options = ['directory',
 
2771
    takes_options = [
3285
2772
        Option('format',
3286
2773
               help="Type of file to export to.",
3287
2774
               type=unicode),
3291
2778
        Option('root',
3292
2779
               type=str,
3293
2780
               help="Name of the root directory inside the exported file."),
3294
 
        Option('per-file-timestamps',
3295
 
               help='Set modification time of files to that of the last '
3296
 
                    'revision in which it was changed.'),
3297
 
        Option('uncommitted',
3298
 
               help='Export the working tree contents rather than that of the '
3299
 
                    'last revision.'),
3300
2781
        ]
3301
2782
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
3302
 
        root=None, filters=False, per_file_timestamps=False, uncommitted=False,
3303
 
        directory=u'.'):
 
2783
        root=None, filters=False):
3304
2784
        from bzrlib.export import export
3305
2785
 
3306
2786
        if branch_or_subdir is None:
3307
 
            branch_or_subdir = directory
3308
 
 
3309
 
        (tree, b, subdir) = controldir.ControlDir.open_containing_tree_or_branch(
3310
 
            branch_or_subdir)
3311
 
        if tree is not None:
3312
 
            self.add_cleanup(tree.lock_read().unlock)
3313
 
 
3314
 
        if uncommitted:
3315
 
            if tree is None:
3316
 
                raise errors.BzrCommandError(
3317
 
                    gettext("--uncommitted requires a working tree"))
3318
 
            export_tree = tree
 
2787
            tree = WorkingTree.open_containing(u'.')[0]
 
2788
            b = tree.branch
 
2789
            subdir = None
3319
2790
        else:
3320
 
            export_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
 
2791
            b, subdir = Branch.open_containing(branch_or_subdir)
 
2792
            tree = None
 
2793
 
 
2794
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
3321
2795
        try:
3322
 
            export(export_tree, dest, format, root, subdir, filtered=filters,
3323
 
                   per_file_timestamps=per_file_timestamps)
 
2796
            export(rev_tree, dest, format, root, subdir, filtered=filters)
3324
2797
        except errors.NoSuchExportFormat, e:
3325
 
            raise errors.BzrCommandError(
3326
 
                gettext('Unsupported export format: %s') % e.format)
 
2798
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3327
2799
 
3328
2800
 
3329
2801
class cmd_cat(Command):
3330
 
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
2802
    """Write the contents of a file as of a given revision to standard output.
3331
2803
 
3332
2804
    If no revision is nominated, the last revision is used.
3333
2805
 
3336
2808
    """
3337
2809
 
3338
2810
    _see_also = ['ls']
3339
 
    takes_options = ['directory',
 
2811
    takes_options = [
3340
2812
        Option('name-from-revision', help='The path name in the old tree.'),
3341
2813
        Option('filters', help='Apply content filters to display the '
3342
2814
                'convenience form.'),
3347
2819
 
3348
2820
    @display_command
3349
2821
    def run(self, filename, revision=None, name_from_revision=False,
3350
 
            filters=False, directory=None):
 
2822
            filters=False):
3351
2823
        if revision is not None and len(revision) != 1:
3352
 
            raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3353
 
                                         " one revision specifier"))
 
2824
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
 
2825
                                         " one revision specifier")
3354
2826
        tree, branch, relpath = \
3355
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
3356
 
        self.add_cleanup(branch.lock_read().unlock)
 
2827
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2828
        branch.lock_read()
 
2829
        self.add_cleanup(branch.unlock)
3357
2830
        return self._run(tree, branch, relpath, filename, revision,
3358
2831
                         name_from_revision, filters)
3359
2832
 
3362
2835
        if tree is None:
3363
2836
            tree = b.basis_tree()
3364
2837
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3365
 
        self.add_cleanup(rev_tree.lock_read().unlock)
 
2838
        rev_tree.lock_read()
 
2839
        self.add_cleanup(rev_tree.unlock)
3366
2840
 
3367
2841
        old_file_id = rev_tree.path2id(relpath)
3368
2842
 
3369
 
        # TODO: Split out this code to something that generically finds the
3370
 
        # best id for a path across one or more trees; it's like
3371
 
        # find_ids_across_trees but restricted to find just one. -- mbp
3372
 
        # 20110705.
3373
2843
        if name_from_revision:
3374
2844
            # Try in revision if requested
3375
2845
            if old_file_id is None:
3376
 
                raise errors.BzrCommandError(gettext(
3377
 
                    "{0!r} is not present in revision {1}").format(
 
2846
                raise errors.BzrCommandError(
 
2847
                    "%r is not present in revision %s" % (
3378
2848
                        filename, rev_tree.get_revision_id()))
3379
2849
            else:
3380
 
                actual_file_id = old_file_id
 
2850
                content = rev_tree.get_file_text(old_file_id)
3381
2851
        else:
3382
2852
            cur_file_id = tree.path2id(relpath)
3383
 
            if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3384
 
                actual_file_id = cur_file_id
3385
 
            elif old_file_id is not None:
3386
 
                actual_file_id = old_file_id
3387
 
            else:
3388
 
                raise errors.BzrCommandError(gettext(
3389
 
                    "{0!r} is not present in revision {1}").format(
 
2853
            found = False
 
2854
            if cur_file_id is not None:
 
2855
                # Then try with the actual file id
 
2856
                try:
 
2857
                    content = rev_tree.get_file_text(cur_file_id)
 
2858
                    found = True
 
2859
                except errors.NoSuchId:
 
2860
                    # The actual file id didn't exist at that time
 
2861
                    pass
 
2862
            if not found and old_file_id is not None:
 
2863
                # Finally try with the old file id
 
2864
                content = rev_tree.get_file_text(old_file_id)
 
2865
                found = True
 
2866
            if not found:
 
2867
                # Can't be found anywhere
 
2868
                raise errors.BzrCommandError(
 
2869
                    "%r is not present in revision %s" % (
3390
2870
                        filename, rev_tree.get_revision_id()))
3391
2871
        if filtered:
3392
 
            from bzrlib.filter_tree import ContentFilterTree
3393
 
            filter_tree = ContentFilterTree(rev_tree,
3394
 
                rev_tree._content_filter_stack)
3395
 
            content = filter_tree.get_file_text(actual_file_id)
 
2872
            from bzrlib.filters import (
 
2873
                ContentFilterContext,
 
2874
                filtered_output_bytes,
 
2875
                )
 
2876
            filters = rev_tree._content_filter_stack(relpath)
 
2877
            chunks = content.splitlines(True)
 
2878
            content = filtered_output_bytes(chunks, filters,
 
2879
                ContentFilterContext(relpath, rev_tree))
 
2880
            self.cleanup_now()
 
2881
            self.outf.writelines(content)
3396
2882
        else:
3397
 
            content = rev_tree.get_file_text(actual_file_id)
3398
 
        self.cleanup_now()
3399
 
        self.outf.write(content)
 
2883
            self.cleanup_now()
 
2884
            self.outf.write(content)
3400
2885
 
3401
2886
 
3402
2887
class cmd_local_time_offset(Command):
3403
 
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
2888
    """Show the offset in seconds from GMT to local time."""
3404
2889
    hidden = True
3405
2890
    @display_command
3406
2891
    def run(self):
3407
 
        self.outf.write("%s\n" % osutils.local_time_offset())
 
2892
        print osutils.local_time_offset()
3408
2893
 
3409
2894
 
3410
2895
 
3411
2896
class cmd_commit(Command):
3412
 
    __doc__ = """Commit changes into a new revision.
 
2897
    """Commit changes into a new revision.
3413
2898
 
3414
2899
    An explanatory message needs to be given for each commit. This is
3415
2900
    often done by using the --message option (getting the message from the
3463
2948
      to trigger updates to external systems like bug trackers. The --fixes
3464
2949
      option can be used to record the association between a revision and
3465
2950
      one or more bugs. See ``bzr help bugs`` for details.
 
2951
 
 
2952
      A selective commit may fail in some cases where the committed
 
2953
      tree would be invalid. Consider::
 
2954
  
 
2955
        bzr init foo
 
2956
        mkdir foo/bar
 
2957
        bzr add foo/bar
 
2958
        bzr commit foo -m "committing foo"
 
2959
        bzr mv foo/bar foo/baz
 
2960
        mkdir foo/bar
 
2961
        bzr add foo/bar
 
2962
        bzr commit foo/bar -m "committing bar but not baz"
 
2963
  
 
2964
      In the example above, the last commit will fail by design. This gives
 
2965
      the user the opportunity to decide whether they want to commit the
 
2966
      rename at the same time, separately first, or not at all. (As a general
 
2967
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
3466
2968
    """
 
2969
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
2970
 
 
2971
    # TODO: Strict commit that fails if there are deleted files.
 
2972
    #       (what does "deleted files" mean ??)
 
2973
 
 
2974
    # TODO: Give better message for -s, --summary, used by tla people
 
2975
 
 
2976
    # XXX: verbose currently does nothing
3467
2977
 
3468
2978
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
3469
2979
    takes_args = ['selected*']
3498
3008
                         "the master branch until a normal commit "
3499
3009
                         "is performed."
3500
3010
                    ),
3501
 
             Option('show-diff', short_name='p',
 
3011
             Option('show-diff',
3502
3012
                    help='When no message is supplied, show the diff along'
3503
3013
                    ' with the status summary in the message editor.'),
3504
 
             Option('lossy', 
3505
 
                    help='When committing to a foreign version control '
3506
 
                    'system do not push data that can not be natively '
3507
 
                    'represented.'),
3508
3014
             ]
3509
3015
    aliases = ['ci', 'checkin']
3510
3016
 
3511
3017
    def _iter_bug_fix_urls(self, fixes, branch):
3512
 
        default_bugtracker  = None
3513
3018
        # Configure the properties for bug fixing attributes.
3514
3019
        for fixed_bug in fixes:
3515
3020
            tokens = fixed_bug.split(':')
3516
 
            if len(tokens) == 1:
3517
 
                if default_bugtracker is None:
3518
 
                    branch_config = branch.get_config()
3519
 
                    default_bugtracker = branch_config.get_user_option(
3520
 
                        "bugtracker")
3521
 
                if default_bugtracker is None:
3522
 
                    raise errors.BzrCommandError(gettext(
3523
 
                        "No tracker specified for bug %s. Use the form "
3524
 
                        "'tracker:id' or specify a default bug tracker "
3525
 
                        "using the `bugtracker` option.\nSee "
3526
 
                        "\"bzr help bugs\" for more information on this "
3527
 
                        "feature. Commit refused.") % fixed_bug)
3528
 
                tag = default_bugtracker
3529
 
                bug_id = tokens[0]
3530
 
            elif len(tokens) != 2:
3531
 
                raise errors.BzrCommandError(gettext(
 
3021
            if len(tokens) != 2:
 
3022
                raise errors.BzrCommandError(
3532
3023
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
3533
3024
                    "See \"bzr help bugs\" for more information on this "
3534
 
                    "feature.\nCommit refused.") % fixed_bug)
3535
 
            else:
3536
 
                tag, bug_id = tokens
 
3025
                    "feature.\nCommit refused." % fixed_bug)
 
3026
            tag, bug_id = tokens
3537
3027
            try:
3538
3028
                yield bugtracker.get_bug_url(tag, branch, bug_id)
3539
3029
            except errors.UnknownBugTrackerAbbreviation:
3540
 
                raise errors.BzrCommandError(gettext(
3541
 
                    'Unrecognized bug %s. Commit refused.') % fixed_bug)
 
3030
                raise errors.BzrCommandError(
 
3031
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
3542
3032
            except errors.MalformedBugIdentifier, e:
3543
 
                raise errors.BzrCommandError(gettext(
3544
 
                    "%s\nCommit refused.") % (str(e),))
 
3033
                raise errors.BzrCommandError(
 
3034
                    "%s\nCommit refused." % (str(e),))
3545
3035
 
3546
3036
    def run(self, message=None, file=None, verbose=False, selected_list=None,
3547
3037
            unchanged=False, strict=False, local=False, fixes=None,
3548
 
            author=None, show_diff=False, exclude=None, commit_time=None,
3549
 
            lossy=False):
 
3038
            author=None, show_diff=False, exclude=None, commit_time=None):
3550
3039
        from bzrlib.errors import (
3551
3040
            PointlessCommit,
3552
3041
            ConflictsInTree,
3555
3044
        from bzrlib.msgeditor import (
3556
3045
            edit_commit_message_encoded,
3557
3046
            generate_commit_message_template,
3558
 
            make_commit_message_template_encoded,
3559
 
            set_commit_message,
 
3047
            make_commit_message_template_encoded
3560
3048
        )
3561
3049
 
3562
3050
        commit_stamp = offset = None
3564
3052
            try:
3565
3053
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3566
3054
            except ValueError, e:
3567
 
                raise errors.BzrCommandError(gettext(
3568
 
                    "Could not parse --commit-time: " + str(e)))
 
3055
                raise errors.BzrCommandError(
 
3056
                    "Could not parse --commit-time: " + str(e))
 
3057
 
 
3058
        # TODO: Need a blackbox test for invoking the external editor; may be
 
3059
        # slightly problematic to run this cross-platform.
 
3060
 
 
3061
        # TODO: do more checks that the commit will succeed before
 
3062
        # spending the user's valuable time typing a commit message.
3569
3063
 
3570
3064
        properties = {}
3571
3065
 
3572
 
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
3066
        tree, selected_list = tree_files(selected_list)
3573
3067
        if selected_list == ['']:
3574
3068
            # workaround - commit of root of tree should be exactly the same
3575
3069
            # as just default commit in that tree, and succeed even though
3600
3094
                    '(use --file "%(f)s" to take commit message from that file)'
3601
3095
                    % { 'f': message })
3602
3096
                ui.ui_factory.show_warning(warning_msg)
3603
 
            if '\r' in message:
3604
 
                message = message.replace('\r\n', '\n')
3605
 
                message = message.replace('\r', '\n')
3606
 
            if file:
3607
 
                raise errors.BzrCommandError(gettext(
3608
 
                    "please specify either --message or --file"))
3609
3097
 
3610
3098
        def get_message(commit_obj):
3611
3099
            """Callback to get commit message"""
3612
 
            if file:
3613
 
                f = open(file)
3614
 
                try:
3615
 
                    my_message = f.read().decode(osutils.get_user_encoding())
3616
 
                finally:
3617
 
                    f.close()
3618
 
            elif message is not None:
3619
 
                my_message = message
3620
 
            else:
3621
 
                # No message supplied: make one up.
3622
 
                # text is the status of the tree
3623
 
                text = make_commit_message_template_encoded(tree,
 
3100
            my_message = message
 
3101
            if my_message is not None and '\r' in my_message:
 
3102
                my_message = my_message.replace('\r\n', '\n')
 
3103
                my_message = my_message.replace('\r', '\n')
 
3104
            if my_message is None and not file:
 
3105
                t = make_commit_message_template_encoded(tree,
3624
3106
                        selected_list, diff=show_diff,
3625
3107
                        output_encoding=osutils.get_user_encoding())
3626
 
                # start_message is the template generated from hooks
3627
 
                # XXX: Warning - looks like hooks return unicode,
3628
 
                # make_commit_message_template_encoded returns user encoding.
3629
 
                # We probably want to be using edit_commit_message instead to
3630
 
                # avoid this.
3631
 
                my_message = set_commit_message(commit_obj)
3632
 
                if my_message is None:
3633
 
                    start_message = generate_commit_message_template(commit_obj)
3634
 
                    my_message = edit_commit_message_encoded(text,
3635
 
                        start_message=start_message)
3636
 
                if my_message is None:
3637
 
                    raise errors.BzrCommandError(gettext("please specify a commit"
3638
 
                        " message with either --message or --file"))
3639
 
                if my_message == "":
3640
 
                    raise errors.BzrCommandError(gettext("Empty commit message specified."
3641
 
                            " Please specify a commit message with either"
3642
 
                            " --message or --file or leave a blank message"
3643
 
                            " with --message \"\"."))
 
3108
                start_message = generate_commit_message_template(commit_obj)
 
3109
                my_message = edit_commit_message_encoded(t,
 
3110
                    start_message=start_message)
 
3111
                if my_message is None:
 
3112
                    raise errors.BzrCommandError("please specify a commit"
 
3113
                        " message with either --message or --file")
 
3114
            elif my_message and file:
 
3115
                raise errors.BzrCommandError(
 
3116
                    "please specify either --message or --file")
 
3117
            if file:
 
3118
                my_message = codecs.open(file, 'rt',
 
3119
                                         osutils.get_user_encoding()).read()
 
3120
            if my_message == "":
 
3121
                raise errors.BzrCommandError("empty commit message specified")
3644
3122
            return my_message
3645
3123
 
3646
3124
        # The API permits a commit with a filter of [] to mean 'select nothing'
3654
3132
                        reporter=None, verbose=verbose, revprops=properties,
3655
3133
                        authors=author, timestamp=commit_stamp,
3656
3134
                        timezone=offset,
3657
 
                        exclude=tree.safe_relpath_files(exclude),
3658
 
                        lossy=lossy)
 
3135
                        exclude=safe_relpath_files(tree, exclude))
3659
3136
        except PointlessCommit:
3660
 
            raise errors.BzrCommandError(gettext("No changes to commit."
3661
 
                " Please 'bzr add' the files you want to commit, or use"
3662
 
                " --unchanged to force an empty commit."))
 
3137
            # FIXME: This should really happen before the file is read in;
 
3138
            # perhaps prepare the commit; get the message; then actually commit
 
3139
            raise errors.BzrCommandError("No changes to commit."
 
3140
                              " Use --unchanged to commit anyhow.")
3663
3141
        except ConflictsInTree:
3664
 
            raise errors.BzrCommandError(gettext('Conflicts detected in working '
 
3142
            raise errors.BzrCommandError('Conflicts detected in working '
3665
3143
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3666
 
                ' resolve.'))
 
3144
                ' resolve.')
3667
3145
        except StrictCommitFailed:
3668
 
            raise errors.BzrCommandError(gettext("Commit refused because there are"
3669
 
                              " unknown files in the working tree."))
 
3146
            raise errors.BzrCommandError("Commit refused because there are"
 
3147
                              " unknown files in the working tree.")
3670
3148
        except errors.BoundBranchOutOfDate, e:
3671
 
            e.extra_help = (gettext("\n"
3672
 
                'To commit to master branch, run update and then commit.\n'
3673
 
                'You can also pass --local to commit to continue working '
3674
 
                'disconnected.'))
3675
 
            raise
 
3149
            raise errors.BzrCommandError(str(e) + "\n"
 
3150
            'To commit to master branch, run update and then commit.\n'
 
3151
            'You can also pass --local to commit to continue working '
 
3152
            'disconnected.')
3676
3153
 
3677
3154
 
3678
3155
class cmd_check(Command):
3679
 
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3156
    """Validate working tree structure, branch consistency and repository history.
3680
3157
 
3681
3158
    This command checks various invariants about branch and repository storage
3682
3159
    to detect data corruption or bzr bugs.
3746
3223
 
3747
3224
 
3748
3225
class cmd_upgrade(Command):
3749
 
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
3750
 
 
3751
 
    When the default format has changed after a major new release of
3752
 
    Bazaar, you may be informed during certain operations that you
3753
 
    should upgrade. Upgrading to a newer format may improve performance
3754
 
    or make new features available. It may however limit interoperability
3755
 
    with older repositories or with older versions of Bazaar.
3756
 
 
3757
 
    If you wish to upgrade to a particular format rather than the
3758
 
    current default, that can be specified using the --format option.
3759
 
    As a consequence, you can use the upgrade command this way to
3760
 
    "downgrade" to an earlier format, though some conversions are
3761
 
    a one way process (e.g. changing from the 1.x default to the
3762
 
    2.x default) so downgrading is not always possible.
3763
 
 
3764
 
    A backup.bzr.~#~ directory is created at the start of the conversion
3765
 
    process (where # is a number). By default, this is left there on
3766
 
    completion. If the conversion fails, delete the new .bzr directory
3767
 
    and rename this one back in its place. Use the --clean option to ask
3768
 
    for the backup.bzr directory to be removed on successful conversion.
3769
 
    Alternatively, you can delete it by hand if everything looks good
3770
 
    afterwards.
3771
 
 
3772
 
    If the location given is a shared repository, dependent branches
3773
 
    are also converted provided the repository converts successfully.
3774
 
    If the conversion of a branch fails, remaining branches are still
3775
 
    tried.
3776
 
 
3777
 
    For more information on upgrades, see the Bazaar Upgrade Guide,
3778
 
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
 
3226
    """Upgrade branch storage to current format.
 
3227
 
 
3228
    The check command or bzr developers may sometimes advise you to run
 
3229
    this command. When the default format has changed you may also be warned
 
3230
    during other operations to upgrade.
3779
3231
    """
3780
3232
 
3781
 
    _see_also = ['check', 'reconcile', 'formats']
 
3233
    _see_also = ['check']
3782
3234
    takes_args = ['url?']
3783
3235
    takes_options = [
3784
 
        RegistryOption('format',
3785
 
            help='Upgrade to a specific format.  See "bzr help'
3786
 
                 ' formats" for details.',
3787
 
            lazy_registry=('bzrlib.controldir', 'format_registry'),
3788
 
            converter=lambda name: controldir.format_registry.make_bzrdir(name),
3789
 
            value_switches=True, title='Branch format'),
3790
 
        Option('clean',
3791
 
            help='Remove the backup.bzr directory if successful.'),
3792
 
        Option('dry-run',
3793
 
            help="Show what would be done, but don't actually do anything."),
3794
 
    ]
 
3236
                    RegistryOption('format',
 
3237
                        help='Upgrade to a specific format.  See "bzr help'
 
3238
                             ' formats" for details.',
 
3239
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3240
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
 
3241
                        value_switches=True, title='Branch format'),
 
3242
                    ]
3795
3243
 
3796
 
    def run(self, url='.', format=None, clean=False, dry_run=False):
 
3244
    def run(self, url='.', format=None):
3797
3245
        from bzrlib.upgrade import upgrade
3798
 
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3799
 
        if exceptions:
3800
 
            if len(exceptions) == 1:
3801
 
                # Compatibility with historical behavior
3802
 
                raise exceptions[0]
3803
 
            else:
3804
 
                return 3
 
3246
        upgrade(url, format)
3805
3247
 
3806
3248
 
3807
3249
class cmd_whoami(Command):
3808
 
    __doc__ = """Show or set bzr user id.
 
3250
    """Show or set bzr user id.
3809
3251
 
3810
3252
    :Examples:
3811
3253
        Show the email of the current user::
3816
3258
 
3817
3259
            bzr whoami "Frank Chu <fchu@example.com>"
3818
3260
    """
3819
 
    takes_options = [ 'directory',
3820
 
                      Option('email',
 
3261
    takes_options = [ Option('email',
3821
3262
                             help='Display email address only.'),
3822
3263
                      Option('branch',
3823
3264
                             help='Set identity for the current branch instead of '
3827
3268
    encoding_type = 'replace'
3828
3269
 
3829
3270
    @display_command
3830
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
3271
    def run(self, email=False, branch=False, name=None):
3831
3272
        if name is None:
3832
 
            if directory is None:
3833
 
                # use branch if we're inside one; otherwise global config
3834
 
                try:
3835
 
                    c = Branch.open_containing(u'.')[0].get_config_stack()
3836
 
                except errors.NotBranchError:
3837
 
                    c = _mod_config.GlobalStack()
3838
 
            else:
3839
 
                c = Branch.open(directory).get_config_stack()
3840
 
            identity = c.get('email')
 
3273
            # use branch if we're inside one; otherwise global config
 
3274
            try:
 
3275
                c = Branch.open_containing('.')[0].get_config()
 
3276
            except errors.NotBranchError:
 
3277
                c = config.GlobalConfig()
3841
3278
            if email:
3842
 
                self.outf.write(_mod_config.extract_email_address(identity)
3843
 
                                + '\n')
 
3279
                self.outf.write(c.user_email() + '\n')
3844
3280
            else:
3845
 
                self.outf.write(identity + '\n')
 
3281
                self.outf.write(c.username() + '\n')
3846
3282
            return
3847
3283
 
3848
 
        if email:
3849
 
            raise errors.BzrCommandError(gettext("--email can only be used to display existing "
3850
 
                                         "identity"))
3851
 
 
3852
3284
        # display a warning if an email address isn't included in the given name.
3853
3285
        try:
3854
 
            _mod_config.extract_email_address(name)
 
3286
            config.extract_email_address(name)
3855
3287
        except errors.NoEmailInUsername, e:
3856
3288
            warning('"%s" does not seem to contain an email address.  '
3857
3289
                    'This is allowed, but not recommended.', name)
3858
3290
 
3859
3291
        # use global config unless --branch given
3860
3292
        if branch:
3861
 
            if directory is None:
3862
 
                c = Branch.open_containing(u'.')[0].get_config_stack()
3863
 
            else:
3864
 
                c = Branch.open(directory).get_config_stack()
 
3293
            c = Branch.open_containing('.')[0].get_config()
3865
3294
        else:
3866
 
            c = _mod_config.GlobalStack()
3867
 
        c.set('email', name)
 
3295
            c = config.GlobalConfig()
 
3296
        c.set_user_option('email', name)
3868
3297
 
3869
3298
 
3870
3299
class cmd_nick(Command):
3871
 
    __doc__ = """Print or set the branch nickname.
 
3300
    """Print or set the branch nickname.
3872
3301
 
3873
3302
    If unset, the tree root directory name is used as the nickname.
3874
3303
    To print the current nickname, execute with no argument.
3879
3308
 
3880
3309
    _see_also = ['info']
3881
3310
    takes_args = ['nickname?']
3882
 
    takes_options = ['directory']
3883
 
    def run(self, nickname=None, directory=u'.'):
3884
 
        branch = Branch.open_containing(directory)[0]
 
3311
    def run(self, nickname=None):
 
3312
        branch = Branch.open_containing(u'.')[0]
3885
3313
        if nickname is None:
3886
3314
            self.printme(branch)
3887
3315
        else:
3889
3317
 
3890
3318
    @display_command
3891
3319
    def printme(self, branch):
3892
 
        self.outf.write('%s\n' % branch.nick)
 
3320
        print branch.nick
3893
3321
 
3894
3322
 
3895
3323
class cmd_alias(Command):
3896
 
    __doc__ = """Set/unset and display aliases.
 
3324
    """Set/unset and display aliases.
3897
3325
 
3898
3326
    :Examples:
3899
3327
        Show the current aliases::
3932
3360
 
3933
3361
    def remove_alias(self, alias_name):
3934
3362
        if alias_name is None:
3935
 
            raise errors.BzrCommandError(gettext(
3936
 
                'bzr alias --remove expects an alias to remove.'))
 
3363
            raise errors.BzrCommandError(
 
3364
                'bzr alias --remove expects an alias to remove.')
3937
3365
        # If alias is not found, print something like:
3938
3366
        # unalias: foo: not found
3939
 
        c = _mod_config.GlobalConfig()
 
3367
        c = config.GlobalConfig()
3940
3368
        c.unset_alias(alias_name)
3941
3369
 
3942
3370
    @display_command
3943
3371
    def print_aliases(self):
3944
3372
        """Print out the defined aliases in a similar format to bash."""
3945
 
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3373
        aliases = config.GlobalConfig().get_aliases()
3946
3374
        for key, value in sorted(aliases.iteritems()):
3947
3375
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3948
3376
 
3958
3386
 
3959
3387
    def set_alias(self, alias_name, alias_command):
3960
3388
        """Save the alias in the global config."""
3961
 
        c = _mod_config.GlobalConfig()
 
3389
        c = config.GlobalConfig()
3962
3390
        c.set_alias(alias_name, alias_command)
3963
3391
 
3964
3392
 
3965
3393
class cmd_selftest(Command):
3966
 
    __doc__ = """Run internal test suite.
 
3394
    """Run internal test suite.
3967
3395
 
3968
3396
    If arguments are given, they are regular expressions that say which tests
3969
3397
    should run.  Tests matching any expression are run, and other tests are
3999
3427
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
4000
3428
    into a pdb postmortem session.
4001
3429
 
4002
 
    The --coverage=DIRNAME global option produces a report with covered code
4003
 
    indicated.
4004
 
 
4005
3430
    :Examples:
4006
3431
        Run only tests relating to 'ignore'::
4007
3432
 
4016
3441
    def get_transport_type(typestring):
4017
3442
        """Parse and return a transport specifier."""
4018
3443
        if typestring == "sftp":
4019
 
            from bzrlib.tests import stub_sftp
4020
 
            return stub_sftp.SFTPAbsoluteServer
4021
 
        elif typestring == "memory":
4022
 
            from bzrlib.tests import test_server
4023
 
            return memory.MemoryServer
4024
 
        elif typestring == "fakenfs":
4025
 
            from bzrlib.tests import test_server
4026
 
            return test_server.FakeNFSServer
 
3444
            from bzrlib.transport.sftp import SFTPAbsoluteServer
 
3445
            return SFTPAbsoluteServer
 
3446
        if typestring == "memory":
 
3447
            from bzrlib.transport.memory import MemoryServer
 
3448
            return MemoryServer
 
3449
        if typestring == "fakenfs":
 
3450
            from bzrlib.transport.fakenfs import FakeNFSServer
 
3451
            return FakeNFSServer
4027
3452
        msg = "No known transport type %s. Supported types are: sftp\n" %\
4028
3453
            (typestring)
4029
3454
        raise errors.BzrCommandError(msg)
4040
3465
                                 'throughout the test suite.',
4041
3466
                            type=get_transport_type),
4042
3467
                     Option('benchmark',
4043
 
                            help='Run the benchmarks rather than selftests.',
4044
 
                            hidden=True),
 
3468
                            help='Run the benchmarks rather than selftests.'),
4045
3469
                     Option('lsprof-timed',
4046
3470
                            help='Generate lsprof output for benchmarked'
4047
3471
                                 ' sections of code.'),
4048
3472
                     Option('lsprof-tests',
4049
3473
                            help='Generate lsprof output for each test.'),
 
3474
                     Option('cache-dir', type=str,
 
3475
                            help='Cache intermediate benchmark output in this '
 
3476
                                 'directory.'),
4050
3477
                     Option('first',
4051
3478
                            help='Run all tests, but run specified tests first.',
4052
3479
                            short_name='f',
4061
3488
                     Option('randomize', type=str, argname="SEED",
4062
3489
                            help='Randomize the order of tests using the given'
4063
3490
                                 ' seed or "now" for the current time.'),
4064
 
                     ListOption('exclude', type=str, argname="PATTERN",
4065
 
                                short_name='x',
4066
 
                                help='Exclude tests that match this regular'
4067
 
                                ' expression.'),
 
3491
                     Option('exclude', type=str, argname="PATTERN",
 
3492
                            short_name='x',
 
3493
                            help='Exclude tests that match this regular'
 
3494
                                 ' expression.'),
4068
3495
                     Option('subunit',
4069
3496
                        help='Output test progress via subunit.'),
4070
3497
                     Option('strict', help='Fail on missing dependencies or '
4077
3504
                                param_name='starting_with', short_name='s',
4078
3505
                                help=
4079
3506
                                'Load only the tests starting with TESTID.'),
4080
 
                     Option('sync',
4081
 
                            help="By default we disable fsync and fdatasync"
4082
 
                                 " while running the test suite.")
4083
3507
                     ]
4084
3508
    encoding_type = 'replace'
4085
3509
 
4089
3513
 
4090
3514
    def run(self, testspecs_list=None, verbose=False, one=False,
4091
3515
            transport=None, benchmark=None,
4092
 
            lsprof_timed=None,
 
3516
            lsprof_timed=None, cache_dir=None,
4093
3517
            first=False, list_only=False,
4094
3518
            randomize=None, exclude=None, strict=False,
4095
3519
            load_list=None, debugflag=None, starting_with=None, subunit=False,
4096
 
            parallel=None, lsprof_tests=False,
4097
 
            sync=False):
4098
 
 
4099
 
        # During selftest, disallow proxying, as it can cause severe
4100
 
        # performance penalties and is only needed for thread
4101
 
        # safety. The selftest command is assumed to not use threads
4102
 
        # too heavily. The call should be as early as possible, as
4103
 
        # error reporting for past duplicate imports won't have useful
4104
 
        # backtraces.
4105
 
        lazy_import.disallow_proxying()
4106
 
 
4107
 
        from bzrlib import tests
4108
 
 
 
3520
            parallel=None, lsprof_tests=False):
 
3521
        from bzrlib.tests import selftest
 
3522
        import bzrlib.benchmarks as benchmarks
 
3523
        from bzrlib.benchmarks import tree_creator
 
3524
 
 
3525
        # Make deprecation warnings visible, unless -Werror is set
 
3526
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3527
 
 
3528
        if cache_dir is not None:
 
3529
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
4109
3530
        if testspecs_list is not None:
4110
3531
            pattern = '|'.join(testspecs_list)
4111
3532
        else:
4114
3535
            try:
4115
3536
                from bzrlib.tests import SubUnitBzrRunner
4116
3537
            except ImportError:
4117
 
                raise errors.BzrCommandError(gettext("subunit not available. subunit "
4118
 
                    "needs to be installed to use --subunit."))
 
3538
                raise errors.BzrCommandError("subunit not available. subunit "
 
3539
                    "needs to be installed to use --subunit.")
4119
3540
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
4120
 
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
4121
 
            # stdout, which would corrupt the subunit stream. 
4122
 
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
4123
 
            # following code can be deleted when it's sufficiently deployed
4124
 
            # -- vila/mgz 20100514
4125
 
            if (sys.platform == "win32"
4126
 
                and getattr(sys.stdout, 'fileno', None) is not None):
4127
 
                import msvcrt
4128
 
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
4129
3541
        if parallel:
4130
3542
            self.additional_selftest_args.setdefault(
4131
3543
                'suite_decorators', []).append(parallel)
4132
3544
        if benchmark:
4133
 
            raise errors.BzrCommandError(gettext(
4134
 
                "--benchmark is no longer supported from bzr 2.2; "
4135
 
                "use bzr-usertest instead"))
4136
 
        test_suite_factory = None
4137
 
        if not exclude:
4138
 
            exclude_pattern = None
 
3545
            test_suite_factory = benchmarks.test_suite
 
3546
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3547
            verbose = not is_quiet()
 
3548
            # TODO: should possibly lock the history file...
 
3549
            benchfile = open(".perf_history", "at", buffering=1)
 
3550
            self.add_cleanup(benchfile.close)
4139
3551
        else:
4140
 
            exclude_pattern = '(' + '|'.join(exclude) + ')'
4141
 
        if not sync:
4142
 
            self._disable_fsync()
 
3552
            test_suite_factory = None
 
3553
            benchfile = None
4143
3554
        selftest_kwargs = {"verbose": verbose,
4144
3555
                          "pattern": pattern,
4145
3556
                          "stop_on_failure": one,
4147
3558
                          "test_suite_factory": test_suite_factory,
4148
3559
                          "lsprof_timed": lsprof_timed,
4149
3560
                          "lsprof_tests": lsprof_tests,
 
3561
                          "bench_history": benchfile,
4150
3562
                          "matching_tests_first": first,
4151
3563
                          "list_only": list_only,
4152
3564
                          "random_seed": randomize,
4153
 
                          "exclude_pattern": exclude_pattern,
 
3565
                          "exclude_pattern": exclude,
4154
3566
                          "strict": strict,
4155
3567
                          "load_list": load_list,
4156
3568
                          "debug_flags": debugflag,
4157
3569
                          "starting_with": starting_with
4158
3570
                          }
4159
3571
        selftest_kwargs.update(self.additional_selftest_args)
4160
 
 
4161
 
        # Make deprecation warnings visible, unless -Werror is set
4162
 
        cleanup = symbol_versioning.activate_deprecation_warnings(
4163
 
            override=False)
4164
 
        try:
4165
 
            result = tests.selftest(**selftest_kwargs)
4166
 
        finally:
4167
 
            cleanup()
 
3572
        result = selftest(**selftest_kwargs)
4168
3573
        return int(not result)
4169
3574
 
4170
 
    def _disable_fsync(self):
4171
 
        """Change the 'os' functionality to not synchronize."""
4172
 
        self._orig_fsync = getattr(os, 'fsync', None)
4173
 
        if self._orig_fsync is not None:
4174
 
            os.fsync = lambda filedes: None
4175
 
        self._orig_fdatasync = getattr(os, 'fdatasync', None)
4176
 
        if self._orig_fdatasync is not None:
4177
 
            os.fdatasync = lambda filedes: None
4178
 
 
4179
3575
 
4180
3576
class cmd_version(Command):
4181
 
    __doc__ = """Show version of bzr."""
 
3577
    """Show version of bzr."""
4182
3578
 
4183
3579
    encoding_type = 'replace'
4184
3580
    takes_options = [
4195
3591
 
4196
3592
 
4197
3593
class cmd_rocks(Command):
4198
 
    __doc__ = """Statement of optimism."""
 
3594
    """Statement of optimism."""
4199
3595
 
4200
3596
    hidden = True
4201
3597
 
4202
3598
    @display_command
4203
3599
    def run(self):
4204
 
        self.outf.write(gettext("It sure does!\n"))
 
3600
        print "It sure does!"
4205
3601
 
4206
3602
 
4207
3603
class cmd_find_merge_base(Command):
4208
 
    __doc__ = """Find and print a base revision for merging two branches."""
 
3604
    """Find and print a base revision for merging two branches."""
4209
3605
    # TODO: Options to specify revisions on either side, as if
4210
3606
    #       merging only part of the history.
4211
3607
    takes_args = ['branch', 'other']
4217
3613
 
4218
3614
        branch1 = Branch.open_containing(branch)[0]
4219
3615
        branch2 = Branch.open_containing(other)[0]
4220
 
        self.add_cleanup(branch1.lock_read().unlock)
4221
 
        self.add_cleanup(branch2.lock_read().unlock)
 
3616
        branch1.lock_read()
 
3617
        self.add_cleanup(branch1.unlock)
 
3618
        branch2.lock_read()
 
3619
        self.add_cleanup(branch2.unlock)
4222
3620
        last1 = ensure_null(branch1.last_revision())
4223
3621
        last2 = ensure_null(branch2.last_revision())
4224
3622
 
4225
3623
        graph = branch1.repository.get_graph(branch2.repository)
4226
3624
        base_rev_id = graph.find_unique_lca(last1, last2)
4227
3625
 
4228
 
        self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
 
3626
        print 'merge base is revision %s' % base_rev_id
4229
3627
 
4230
3628
 
4231
3629
class cmd_merge(Command):
4232
 
    __doc__ = """Perform a three-way merge.
 
3630
    """Perform a three-way merge.
4233
3631
 
4234
3632
    The source of the merge can be specified either in the form of a branch,
4235
3633
    or in the form of a path to a file containing a merge directive generated
4236
3634
    with bzr send. If neither is specified, the default is the upstream branch
4237
 
    or the branch most recently merged using --remember.  The source of the
4238
 
    merge may also be specified in the form of a path to a file in another
4239
 
    branch:  in this case, only the modifications to that file are merged into
4240
 
    the current working tree.
4241
 
 
4242
 
    When merging from a branch, by default bzr will try to merge in all new
4243
 
    work from the other branch, automatically determining an appropriate base
4244
 
    revision.  If this fails, you may need to give an explicit base.
4245
 
 
4246
 
    To pick a different ending revision, pass "--revision OTHER".  bzr will
4247
 
    try to merge in all new work up to and including revision OTHER.
4248
 
 
4249
 
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
4250
 
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
4251
 
    causes some revisions to be skipped, i.e. if the destination branch does
4252
 
    not already contain revision BASE, such a merge is commonly referred to as
4253
 
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4254
 
    cherrypicks. The changes look like a normal commit, and the history of the
4255
 
    changes from the other branch is not stored in the commit.
4256
 
 
4257
 
    Revision numbers are always relative to the source branch.
 
3635
    or the branch most recently merged using --remember.
 
3636
 
 
3637
    When merging a branch, by default the tip will be merged. To pick a different
 
3638
    revision, pass --revision. If you specify two values, the first will be used as
 
3639
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
3640
    available revisions, like this is commonly referred to as "cherrypicking".
 
3641
 
 
3642
    Revision numbers are always relative to the branch being merged.
 
3643
 
 
3644
    By default, bzr will try to merge in all new work from the other
 
3645
    branch, automatically determining an appropriate base.  If this
 
3646
    fails, you may need to give an explicit base.
4258
3647
 
4259
3648
    Merge will do its best to combine the changes in two branches, but there
4260
3649
    are some kinds of problems only a human can fix.  When it encounters those,
4261
3650
    it will mark a conflict.  A conflict means that you need to fix something,
4262
 
    before you can commit.
 
3651
    before you should commit.
4263
3652
 
4264
3653
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
4265
3654
 
4266
 
    If there is no default branch set, the first merge will set it (use
4267
 
    --no-remember to avoid setting it). After that, you can omit the branch
4268
 
    to use the default.  To change the default, use --remember. The value will
4269
 
    only be saved if the remote location can be accessed.
 
3655
    If there is no default branch set, the first merge will set it. After
 
3656
    that, you can omit the branch to use the default.  To change the
 
3657
    default, use --remember. The value will only be saved if the remote
 
3658
    location can be accessed.
4270
3659
 
4271
3660
    The results of the merge are placed into the destination working
4272
3661
    directory, where they can be reviewed (with bzr diff), tested, and then
4273
3662
    committed to record the result of the merge.
4274
3663
 
4275
3664
    merge refuses to run if there are any uncommitted changes, unless
4276
 
    --force is given.  If --force is given, then the changes from the source 
4277
 
    will be merged with the current working tree, including any uncommitted
4278
 
    changes in the tree.  The --force option can also be used to create a
 
3665
    --force is given. The --force option can also be used to create a
4279
3666
    merge revision which has more than two parents.
4280
3667
 
4281
3668
    If one would like to merge changes from the working tree of the other
4286
3673
    you to apply each diff hunk and file change, similar to "shelve".
4287
3674
 
4288
3675
    :Examples:
4289
 
        To merge all new revisions from bzr.dev::
 
3676
        To merge the latest revision from bzr.dev::
4290
3677
 
4291
3678
            bzr merge ../bzr.dev
4292
3679
 
4329
3716
                ' completely merged into the source, pull from the'
4330
3717
                ' source rather than merging.  When this happens,'
4331
3718
                ' you do not need to commit the result.'),
4332
 
        custom_help('directory',
 
3719
        Option('directory',
4333
3720
               help='Branch to merge into, '
4334
 
                    'rather than the one containing the working directory.'),
 
3721
                    'rather than the one containing the working directory.',
 
3722
               short_name='d',
 
3723
               type=unicode,
 
3724
               ),
4335
3725
        Option('preview', help='Instead of merging, show a diff of the'
4336
3726
               ' merge.'),
4337
3727
        Option('interactive', help='Select changes interactively.',
4339
3729
    ]
4340
3730
 
4341
3731
    def run(self, location=None, revision=None, force=False,
4342
 
            merge_type=None, show_base=False, reprocess=None, remember=None,
 
3732
            merge_type=None, show_base=False, reprocess=None, remember=False,
4343
3733
            uncommitted=False, pull=False,
4344
3734
            directory=None,
4345
3735
            preview=False,
4353
3743
        merger = None
4354
3744
        allow_pending = True
4355
3745
        verified = 'inapplicable'
4356
 
 
4357
3746
        tree = WorkingTree.open_containing(directory)[0]
4358
 
        if tree.branch.revno() == 0:
4359
 
            raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
4360
 
                                         'https://bugs.launchpad.net/bzr/+bug/308562'))
4361
3747
 
4362
3748
        try:
4363
3749
            basis_tree = tree.revision_tree(tree.last_revision())
4374
3760
            unversioned_filter=tree.is_ignored, view_info=view_info)
4375
3761
        pb = ui.ui_factory.nested_progress_bar()
4376
3762
        self.add_cleanup(pb.finished)
4377
 
        self.add_cleanup(tree.lock_write().unlock)
 
3763
        tree.lock_write()
 
3764
        self.add_cleanup(tree.unlock)
4378
3765
        if location is not None:
4379
3766
            try:
4380
3767
                mergeable = bundle.read_mergeable_from_url(location,
4383
3770
                mergeable = None
4384
3771
            else:
4385
3772
                if uncommitted:
4386
 
                    raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4387
 
                        ' with bundles or merge directives.'))
 
3773
                    raise errors.BzrCommandError('Cannot use --uncommitted'
 
3774
                        ' with bundles or merge directives.')
4388
3775
 
4389
3776
                if revision is not None:
4390
 
                    raise errors.BzrCommandError(gettext(
4391
 
                        'Cannot use -r with merge directives or bundles'))
 
3777
                    raise errors.BzrCommandError(
 
3778
                        'Cannot use -r with merge directives or bundles')
4392
3779
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
4393
 
                   mergeable, None)
 
3780
                   mergeable, pb)
4394
3781
 
4395
3782
        if merger is None and uncommitted:
4396
3783
            if revision is not None and len(revision) > 0:
4397
 
                raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4398
 
                    ' --revision at the same time.'))
4399
 
            merger = self.get_merger_from_uncommitted(tree, location, None)
 
3784
                raise errors.BzrCommandError('Cannot use --uncommitted and'
 
3785
                    ' --revision at the same time.')
 
3786
            merger = self.get_merger_from_uncommitted(tree, location, pb)
4400
3787
            allow_pending = False
4401
3788
 
4402
3789
        if merger is None:
4403
3790
            merger, allow_pending = self._get_merger_from_branch(tree,
4404
 
                location, revision, remember, possible_transports, None)
 
3791
                location, revision, remember, possible_transports, pb)
4405
3792
 
4406
3793
        merger.merge_type = merge_type
4407
3794
        merger.reprocess = reprocess
4409
3796
        self.sanity_check_merger(merger)
4410
3797
        if (merger.base_rev_id == merger.other_rev_id and
4411
3798
            merger.other_rev_id is not None):
4412
 
            # check if location is a nonexistent file (and not a branch) to
4413
 
            # disambiguate the 'Nothing to do'
4414
 
            if merger.interesting_files:
4415
 
                if not merger.other_tree.has_filename(
4416
 
                    merger.interesting_files[0]):
4417
 
                    note(gettext("merger: ") + str(merger))
4418
 
                    raise errors.PathsDoNotExist([location])
4419
 
            note(gettext('Nothing to do.'))
 
3799
            note('Nothing to do.')
4420
3800
            return 0
4421
 
        if pull and not preview:
 
3801
        if pull:
4422
3802
            if merger.interesting_files is not None:
4423
 
                raise errors.BzrCommandError(gettext('Cannot pull individual files'))
 
3803
                raise errors.BzrCommandError('Cannot pull individual files')
4424
3804
            if (merger.base_rev_id == tree.last_revision()):
4425
3805
                result = tree.pull(merger.other_branch, False,
4426
3806
                                   merger.other_rev_id)
4427
3807
                result.report(self.outf)
4428
3808
                return 0
4429
3809
        if merger.this_basis is None:
4430
 
            raise errors.BzrCommandError(gettext(
 
3810
            raise errors.BzrCommandError(
4431
3811
                "This branch has no commits."
4432
 
                " (perhaps you would prefer 'bzr pull')"))
 
3812
                " (perhaps you would prefer 'bzr pull')")
4433
3813
        if preview:
4434
3814
            return self._do_preview(merger)
4435
3815
        elif interactive:
4448
3828
    def _do_preview(self, merger):
4449
3829
        from bzrlib.diff import show_diff_trees
4450
3830
        result_tree = self._get_preview(merger)
4451
 
        path_encoding = osutils.get_diff_header_encoding()
4452
3831
        show_diff_trees(merger.this_tree, result_tree, self.outf,
4453
 
                        old_label='', new_label='',
4454
 
                        path_encoding=path_encoding)
 
3832
                        old_label='', new_label='')
4455
3833
 
4456
3834
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
4457
3835
        merger.change_reporter = change_reporter
4486
3864
    def sanity_check_merger(self, merger):
4487
3865
        if (merger.show_base and
4488
3866
            not merger.merge_type is _mod_merge.Merge3Merger):
4489
 
            raise errors.BzrCommandError(gettext("Show-base is not supported for this"
4490
 
                                         " merge type. %s") % merger.merge_type)
 
3867
            raise errors.BzrCommandError("Show-base is not supported for this"
 
3868
                                         " merge type. %s" % merger.merge_type)
4491
3869
        if merger.reprocess is None:
4492
3870
            if merger.show_base:
4493
3871
                merger.reprocess = False
4495
3873
                # Use reprocess if the merger supports it
4496
3874
                merger.reprocess = merger.merge_type.supports_reprocess
4497
3875
        if merger.reprocess and not merger.merge_type.supports_reprocess:
4498
 
            raise errors.BzrCommandError(gettext("Conflict reduction is not supported"
4499
 
                                         " for merge type %s.") %
 
3876
            raise errors.BzrCommandError("Conflict reduction is not supported"
 
3877
                                         " for merge type %s." %
4500
3878
                                         merger.merge_type)
4501
3879
        if merger.reprocess and merger.show_base:
4502
 
            raise errors.BzrCommandError(gettext("Cannot do conflict reduction and"
4503
 
                                         " show base."))
 
3880
            raise errors.BzrCommandError("Cannot do conflict reduction and"
 
3881
                                         " show base.")
4504
3882
 
4505
3883
    def _get_merger_from_branch(self, tree, location, revision, remember,
4506
3884
                                possible_transports, pb):
4533
3911
        if other_revision_id is None:
4534
3912
            other_revision_id = _mod_revision.ensure_null(
4535
3913
                other_branch.last_revision())
4536
 
        # Remember where we merge from. We need to remember if:
4537
 
        # - user specify a location (and we don't merge from the parent
4538
 
        #   branch)
4539
 
        # - user ask to remember or there is no previous location set to merge
4540
 
        #   from and user didn't ask to *not* remember
4541
 
        if (user_location is not None
4542
 
            and ((remember
4543
 
                  or (remember is None
4544
 
                      and tree.branch.get_submit_branch() is None)))):
 
3914
        # Remember where we merge from
 
3915
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3916
             user_location is not None):
4545
3917
            tree.branch.set_submit_branch(other_branch.base)
4546
 
        # Merge tags (but don't set them in the master branch yet, the user
4547
 
        # might revert this merge).  Commit will propagate them.
4548
 
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
 
3918
        _merge_tags_if_possible(other_branch, tree.branch)
4549
3919
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4550
3920
            other_revision_id, base_revision_id, other_branch, base_branch)
4551
3921
        if other_path != '':
4610
3980
            stored_location_type = "parent"
4611
3981
        mutter("%s", stored_location)
4612
3982
        if stored_location is None:
4613
 
            raise errors.BzrCommandError(gettext("No location specified or remembered"))
 
3983
            raise errors.BzrCommandError("No location specified or remembered")
4614
3984
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
4615
 
        note(gettext("{0} remembered {1} location {2}").format(verb_string,
4616
 
                stored_location_type, display_url))
 
3985
        note(u"%s remembered %s location %s", verb_string,
 
3986
                stored_location_type, display_url)
4617
3987
        return stored_location
4618
3988
 
4619
3989
 
4620
3990
class cmd_remerge(Command):
4621
 
    __doc__ = """Redo a merge.
 
3991
    """Redo a merge.
4622
3992
 
4623
3993
    Use this if you want to try a different merge technique while resolving
4624
3994
    conflicts.  Some merge techniques are better than others, and remerge
4649
4019
 
4650
4020
    def run(self, file_list=None, merge_type=None, show_base=False,
4651
4021
            reprocess=False):
4652
 
        from bzrlib.conflicts import restore
4653
4022
        if merge_type is None:
4654
4023
            merge_type = _mod_merge.Merge3Merger
4655
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4656
 
        self.add_cleanup(tree.lock_write().unlock)
 
4024
        tree, file_list = tree_files(file_list)
 
4025
        tree.lock_write()
 
4026
        self.add_cleanup(tree.unlock)
4657
4027
        parents = tree.get_parent_ids()
4658
4028
        if len(parents) != 2:
4659
 
            raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
 
4029
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4660
4030
                                         " merges.  Not cherrypicking or"
4661
 
                                         " multi-merges."))
 
4031
                                         " multi-merges.")
4662
4032
        repository = tree.branch.repository
4663
4033
        interesting_ids = None
4664
4034
        new_conflicts = []
4695
4065
        # list, we imply that the working tree text has seen and rejected
4696
4066
        # all the changes from the other tree, when in fact those changes
4697
4067
        # have not yet been seen.
 
4068
        pb = ui.ui_factory.nested_progress_bar()
4698
4069
        tree.set_parent_ids(parents[:1])
4699
4070
        try:
4700
 
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
 
4071
            merger = _mod_merge.Merger.from_revision_ids(pb,
 
4072
                                                         tree, parents[1])
4701
4073
            merger.interesting_ids = interesting_ids
4702
4074
            merger.merge_type = merge_type
4703
4075
            merger.show_base = show_base
4705
4077
            conflicts = merger.do_merge()
4706
4078
        finally:
4707
4079
            tree.set_parent_ids(parents)
 
4080
            pb.finished()
4708
4081
        if conflicts > 0:
4709
4082
            return 1
4710
4083
        else:
4712
4085
 
4713
4086
 
4714
4087
class cmd_revert(Command):
4715
 
    __doc__ = """Revert files to a previous revision.
 
4088
    """Revert files to a previous revision.
4716
4089
 
4717
4090
    Giving a list of files will revert only those files.  Otherwise, all files
4718
4091
    will be reverted.  If the revision is not specified with '--revision', the
4719
4092
    last committed revision is used.
4720
4093
 
4721
4094
    To remove only some changes, without reverting to a prior version, use
4722
 
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
4723
 
    will remove the changes introduced by the second last commit (-2), without
4724
 
    affecting the changes introduced by the last commit (-1).  To remove
4725
 
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
4095
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
4096
    changes introduced by -2, without affecting the changes introduced by -1.
 
4097
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4726
4098
 
4727
4099
    By default, any files that have been manually changed will be backed up
4728
4100
    first.  (Files changed only by merge are not backed up.)  Backup files have
4758
4130
    target branches.
4759
4131
    """
4760
4132
 
4761
 
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4133
    _see_also = ['cat', 'export']
4762
4134
    takes_options = [
4763
4135
        'revision',
4764
4136
        Option('no-backup', "Do not save backups of reverted files."),
4769
4141
 
4770
4142
    def run(self, revision=None, no_backup=False, file_list=None,
4771
4143
            forget_merges=None):
4772
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4773
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
4144
        tree, file_list = tree_files(file_list)
 
4145
        tree.lock_write()
 
4146
        self.add_cleanup(tree.unlock)
4774
4147
        if forget_merges:
4775
4148
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4776
4149
        else:
4779
4152
    @staticmethod
4780
4153
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
4781
4154
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4782
 
        tree.revert(file_list, rev_tree, not no_backup, None,
4783
 
            report_changes=True)
 
4155
        pb = ui.ui_factory.nested_progress_bar()
 
4156
        try:
 
4157
            tree.revert(file_list, rev_tree, not no_backup, pb,
 
4158
                report_changes=True)
 
4159
        finally:
 
4160
            pb.finished()
4784
4161
 
4785
4162
 
4786
4163
class cmd_assert_fail(Command):
4787
 
    __doc__ = """Test reporting of assertion failures"""
 
4164
    """Test reporting of assertion failures"""
4788
4165
    # intended just for use in testing
4789
4166
 
4790
4167
    hidden = True
4794
4171
 
4795
4172
 
4796
4173
class cmd_help(Command):
4797
 
    __doc__ = """Show help on a command or other topic.
 
4174
    """Show help on a command or other topic.
4798
4175
    """
4799
4176
 
4800
4177
    _see_also = ['topics']
4813
4190
 
4814
4191
 
4815
4192
class cmd_shell_complete(Command):
4816
 
    __doc__ = """Show appropriate completions for context.
 
4193
    """Show appropriate completions for context.
4817
4194
 
4818
4195
    For a list of all available commands, say 'bzr shell-complete'.
4819
4196
    """
4823
4200
 
4824
4201
    @display_command
4825
4202
    def run(self, context=None):
4826
 
        from bzrlib import shellcomplete
 
4203
        import shellcomplete
4827
4204
        shellcomplete.shellcomplete(context)
4828
4205
 
4829
4206
 
4830
4207
class cmd_missing(Command):
4831
 
    __doc__ = """Show unmerged/unpulled revisions between two branches.
 
4208
    """Show unmerged/unpulled revisions between two branches.
4832
4209
 
4833
4210
    OTHER_BRANCH may be local or remote.
4834
4211
 
4865
4242
    _see_also = ['merge', 'pull']
4866
4243
    takes_args = ['other_branch?']
4867
4244
    takes_options = [
4868
 
        'directory',
4869
4245
        Option('reverse', 'Reverse the order of revisions.'),
4870
4246
        Option('mine-only',
4871
4247
               'Display changes in the local branch only.'),
4883
4259
            type=_parse_revision_str,
4884
4260
            help='Filter on local branch revisions (inclusive). '
4885
4261
                'See "help revisionspec" for details.'),
4886
 
        Option('include-merged',
 
4262
        Option('include-merges',
4887
4263
               'Show all revisions in addition to the mainline ones.'),
4888
 
        Option('include-merges', hidden=True,
4889
 
               help='Historical alias for --include-merged.'),
4890
4264
        ]
4891
4265
    encoding_type = 'replace'
4892
4266
 
4895
4269
            theirs_only=False,
4896
4270
            log_format=None, long=False, short=False, line=False,
4897
4271
            show_ids=False, verbose=False, this=False, other=False,
4898
 
            include_merged=None, revision=None, my_revision=None,
4899
 
            directory=u'.',
4900
 
            include_merges=symbol_versioning.DEPRECATED_PARAMETER):
 
4272
            include_merges=False, revision=None, my_revision=None):
4901
4273
        from bzrlib.missing import find_unmerged, iter_log_revisions
4902
4274
        def message(s):
4903
4275
            if not is_quiet():
4904
4276
                self.outf.write(s)
4905
4277
 
4906
 
        if symbol_versioning.deprecated_passed(include_merges):
4907
 
            ui.ui_factory.show_user_warning(
4908
 
                'deprecated_command_option',
4909
 
                deprecated_name='--include-merges',
4910
 
                recommended_name='--include-merged',
4911
 
                deprecated_in_version='2.5',
4912
 
                command=self.invoked_as)
4913
 
            if include_merged is None:
4914
 
                include_merged = include_merges
4915
 
            else:
4916
 
                raise errors.BzrCommandError(gettext(
4917
 
                    '{0} and {1} are mutually exclusive').format(
4918
 
                    '--include-merges', '--include-merged'))
4919
 
        if include_merged is None:
4920
 
            include_merged = False
4921
4278
        if this:
4922
4279
            mine_only = this
4923
4280
        if other:
4931
4288
        elif theirs_only:
4932
4289
            restrict = 'remote'
4933
4290
 
4934
 
        local_branch = Branch.open_containing(directory)[0]
4935
 
        self.add_cleanup(local_branch.lock_read().unlock)
4936
 
 
 
4291
        local_branch = Branch.open_containing(u".")[0]
4937
4292
        parent = local_branch.get_parent()
4938
4293
        if other_branch is None:
4939
4294
            other_branch = parent
4940
4295
            if other_branch is None:
4941
 
                raise errors.BzrCommandError(gettext("No peer location known"
4942
 
                                             " or specified."))
 
4296
                raise errors.BzrCommandError("No peer location known"
 
4297
                                             " or specified.")
4943
4298
            display_url = urlutils.unescape_for_display(parent,
4944
4299
                                                        self.outf.encoding)
4945
 
            message(gettext("Using saved parent location: {0}\n").format(
4946
 
                    display_url))
 
4300
            message("Using saved parent location: "
 
4301
                    + display_url + "\n")
4947
4302
 
4948
4303
        remote_branch = Branch.open(other_branch)
4949
4304
        if remote_branch.base == local_branch.base:
4950
4305
            remote_branch = local_branch
4951
 
        else:
4952
 
            self.add_cleanup(remote_branch.lock_read().unlock)
4953
4306
 
 
4307
        local_branch.lock_read()
 
4308
        self.add_cleanup(local_branch.unlock)
4954
4309
        local_revid_range = _revision_range_to_revid_range(
4955
4310
            _get_revision_range(my_revision, local_branch,
4956
4311
                self.name()))
4957
4312
 
 
4313
        remote_branch.lock_read()
 
4314
        self.add_cleanup(remote_branch.unlock)
4958
4315
        remote_revid_range = _revision_range_to_revid_range(
4959
4316
            _get_revision_range(revision,
4960
4317
                remote_branch, self.name()))
4962
4319
        local_extra, remote_extra = find_unmerged(
4963
4320
            local_branch, remote_branch, restrict,
4964
4321
            backward=not reverse,
4965
 
            include_merged=include_merged,
 
4322
            include_merges=include_merges,
4966
4323
            local_revid_range=local_revid_range,
4967
4324
            remote_revid_range=remote_revid_range)
4968
4325
 
4975
4332
 
4976
4333
        status_code = 0
4977
4334
        if local_extra and not theirs_only:
4978
 
            message(ngettext("You have %d extra revision:\n",
4979
 
                             "You have %d extra revisions:\n", 
4980
 
                             len(local_extra)) %
 
4335
            message("You have %d extra revision(s):\n" %
4981
4336
                len(local_extra))
4982
4337
            for revision in iter_log_revisions(local_extra,
4983
4338
                                local_branch.repository,
4991
4346
        if remote_extra and not mine_only:
4992
4347
            if printed_local is True:
4993
4348
                message("\n\n\n")
4994
 
            message(ngettext("You are missing %d revision:\n",
4995
 
                             "You are missing %d revisions:\n",
4996
 
                             len(remote_extra)) %
 
4349
            message("You are missing %d revision(s):\n" %
4997
4350
                len(remote_extra))
4998
4351
            for revision in iter_log_revisions(remote_extra,
4999
4352
                                remote_branch.repository,
5003
4356
 
5004
4357
        if mine_only and not local_extra:
5005
4358
            # We checked local, and found nothing extra
5006
 
            message(gettext('This branch has no new revisions.\n'))
 
4359
            message('This branch is up to date.\n')
5007
4360
        elif theirs_only and not remote_extra:
5008
4361
            # We checked remote, and found nothing extra
5009
 
            message(gettext('Other branch has no new revisions.\n'))
 
4362
            message('Other branch is up to date.\n')
5010
4363
        elif not (mine_only or theirs_only or local_extra or
5011
4364
                  remote_extra):
5012
4365
            # We checked both branches, and neither one had extra
5013
4366
            # revisions
5014
 
            message(gettext("Branches are up to date.\n"))
 
4367
            message("Branches are up to date.\n")
5015
4368
        self.cleanup_now()
5016
4369
        if not status_code and parent is None and other_branch is not None:
5017
 
            self.add_cleanup(local_branch.lock_write().unlock)
 
4370
            local_branch.lock_write()
 
4371
            self.add_cleanup(local_branch.unlock)
5018
4372
            # handle race conditions - a parent might be set while we run.
5019
4373
            if local_branch.get_parent() is None:
5020
4374
                local_branch.set_parent(remote_branch.base)
5022
4376
 
5023
4377
 
5024
4378
class cmd_pack(Command):
5025
 
    __doc__ = """Compress the data within a repository.
5026
 
 
5027
 
    This operation compresses the data within a bazaar repository. As
5028
 
    bazaar supports automatic packing of repository, this operation is
5029
 
    normally not required to be done manually.
5030
 
 
5031
 
    During the pack operation, bazaar takes a backup of existing repository
5032
 
    data, i.e. pack files. This backup is eventually removed by bazaar
5033
 
    automatically when it is safe to do so. To save disk space by removing
5034
 
    the backed up pack files, the --clean-obsolete-packs option may be
5035
 
    used.
5036
 
 
5037
 
    Warning: If you use --clean-obsolete-packs and your machine crashes
5038
 
    during or immediately after repacking, you may be left with a state
5039
 
    where the deletion has been written to disk but the new packs have not
5040
 
    been. In this case the repository may be unusable.
5041
 
    """
 
4379
    """Compress the data within a repository."""
5042
4380
 
5043
4381
    _see_also = ['repositories']
5044
4382
    takes_args = ['branch_or_repo?']
5045
 
    takes_options = [
5046
 
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
5047
 
        ]
5048
4383
 
5049
 
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
5050
 
        dir = controldir.ControlDir.open_containing(branch_or_repo)[0]
 
4384
    def run(self, branch_or_repo='.'):
 
4385
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
5051
4386
        try:
5052
4387
            branch = dir.open_branch()
5053
4388
            repository = branch.repository
5054
4389
        except errors.NotBranchError:
5055
4390
            repository = dir.open_repository()
5056
 
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
4391
        repository.pack()
5057
4392
 
5058
4393
 
5059
4394
class cmd_plugins(Command):
5060
 
    __doc__ = """List the installed plugins.
 
4395
    """List the installed plugins.
5061
4396
 
5062
4397
    This command displays the list of installed plugins including
5063
4398
    version of plugin and a short description of each.
5079
4414
 
5080
4415
    @display_command
5081
4416
    def run(self, verbose=False):
5082
 
        from bzrlib import plugin
5083
 
        # Don't give writelines a generator as some codecs don't like that
5084
 
        self.outf.writelines(
5085
 
            list(plugin.describe_plugins(show_paths=verbose)))
 
4417
        import bzrlib.plugin
 
4418
        from inspect import getdoc
 
4419
        result = []
 
4420
        for name, plugin in bzrlib.plugin.plugins().items():
 
4421
            version = plugin.__version__
 
4422
            if version == 'unknown':
 
4423
                version = ''
 
4424
            name_ver = '%s %s' % (name, version)
 
4425
            d = getdoc(plugin.module)
 
4426
            if d:
 
4427
                doc = d.split('\n')[0]
 
4428
            else:
 
4429
                doc = '(no description)'
 
4430
            result.append((name_ver, doc, plugin.path()))
 
4431
        for name_ver, doc, path in sorted(result):
 
4432
            print name_ver
 
4433
            print '   ', doc
 
4434
            if verbose:
 
4435
                print '   ', path
 
4436
            print
5086
4437
 
5087
4438
 
5088
4439
class cmd_testament(Command):
5089
 
    __doc__ = """Show testament (signing-form) of a revision."""
 
4440
    """Show testament (signing-form) of a revision."""
5090
4441
    takes_options = [
5091
4442
            'revision',
5092
4443
            Option('long', help='Produce long-format testament.'),
5104
4455
            b = Branch.open_containing(branch)[0]
5105
4456
        else:
5106
4457
            b = Branch.open(branch)
5107
 
        self.add_cleanup(b.lock_read().unlock)
 
4458
        b.lock_read()
 
4459
        self.add_cleanup(b.unlock)
5108
4460
        if revision is None:
5109
4461
            rev_id = b.last_revision()
5110
4462
        else:
5117
4469
 
5118
4470
 
5119
4471
class cmd_annotate(Command):
5120
 
    __doc__ = """Show the origin of each line in a file.
 
4472
    """Show the origin of each line in a file.
5121
4473
 
5122
4474
    This prints out the given file with an annotation on the left side
5123
4475
    indicating which revision, author and date introduced the change.
5134
4486
                     Option('long', help='Show commit date in annotations.'),
5135
4487
                     'revision',
5136
4488
                     'show-ids',
5137
 
                     'directory',
5138
4489
                     ]
5139
4490
    encoding_type = 'exact'
5140
4491
 
5141
4492
    @display_command
5142
4493
    def run(self, filename, all=False, long=False, revision=None,
5143
 
            show_ids=False, directory=None):
5144
 
        from bzrlib.annotate import (
5145
 
            annotate_file_tree,
5146
 
            )
 
4494
            show_ids=False):
 
4495
        from bzrlib.annotate import annotate_file, annotate_file_tree
5147
4496
        wt, branch, relpath = \
5148
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4497
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
5149
4498
        if wt is not None:
5150
 
            self.add_cleanup(wt.lock_read().unlock)
 
4499
            wt.lock_read()
 
4500
            self.add_cleanup(wt.unlock)
5151
4501
        else:
5152
 
            self.add_cleanup(branch.lock_read().unlock)
 
4502
            branch.lock_read()
 
4503
            self.add_cleanup(branch.unlock)
5153
4504
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
5154
 
        self.add_cleanup(tree.lock_read().unlock)
5155
 
        if wt is not None and revision is None:
 
4505
        tree.lock_read()
 
4506
        self.add_cleanup(tree.unlock)
 
4507
        if wt is not None:
5156
4508
            file_id = wt.path2id(relpath)
5157
4509
        else:
5158
4510
            file_id = tree.path2id(relpath)
5159
4511
        if file_id is None:
5160
4512
            raise errors.NotVersionedError(filename)
 
4513
        file_version = tree.inventory[file_id].revision
5161
4514
        if wt is not None and revision is None:
5162
4515
            # If there is a tree and we're not annotating historical
5163
4516
            # versions, annotate the working tree's content.
5164
4517
            annotate_file_tree(wt, file_id, self.outf, long, all,
5165
4518
                show_ids=show_ids)
5166
4519
        else:
5167
 
            annotate_file_tree(tree, file_id, self.outf, long, all,
5168
 
                show_ids=show_ids, branch=branch)
 
4520
            annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4521
                          show_ids=show_ids)
5169
4522
 
5170
4523
 
5171
4524
class cmd_re_sign(Command):
5172
 
    __doc__ = """Create a digital signature for an existing revision."""
 
4525
    """Create a digital signature for an existing revision."""
5173
4526
    # TODO be able to replace existing ones.
5174
4527
 
5175
4528
    hidden = True # is this right ?
5176
4529
    takes_args = ['revision_id*']
5177
 
    takes_options = ['directory', 'revision']
 
4530
    takes_options = ['revision']
5178
4531
 
5179
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
4532
    def run(self, revision_id_list=None, revision=None):
5180
4533
        if revision_id_list is not None and revision is not None:
5181
 
            raise errors.BzrCommandError(gettext('You can only supply one of revision_id or --revision'))
 
4534
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
5182
4535
        if revision_id_list is None and revision is None:
5183
 
            raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
5184
 
        b = WorkingTree.open_containing(directory)[0].branch
5185
 
        self.add_cleanup(b.lock_write().unlock)
 
4536
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
 
4537
        b = WorkingTree.open_containing(u'.')[0].branch
 
4538
        b.lock_write()
 
4539
        self.add_cleanup(b.unlock)
5186
4540
        return self._run(b, revision_id_list, revision)
5187
4541
 
5188
4542
    def _run(self, b, revision_id_list, revision):
5189
4543
        import bzrlib.gpg as gpg
5190
 
        gpg_strategy = gpg.GPGStrategy(b.get_config_stack())
 
4544
        gpg_strategy = gpg.GPGStrategy(b.get_config())
5191
4545
        if revision_id_list is not None:
5192
4546
            b.repository.start_write_group()
5193
4547
            try:
5218
4572
                if to_revid is None:
5219
4573
                    to_revno = b.revno()
5220
4574
                if from_revno is None or to_revno is None:
5221
 
                    raise errors.BzrCommandError(gettext('Cannot sign a range of non-revision-history revisions'))
 
4575
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
5222
4576
                b.repository.start_write_group()
5223
4577
                try:
5224
4578
                    for revno in range(from_revno, to_revno + 1):
5230
4584
                else:
5231
4585
                    b.repository.commit_write_group()
5232
4586
            else:
5233
 
                raise errors.BzrCommandError(gettext('Please supply either one revision, or a range.'))
 
4587
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
5234
4588
 
5235
4589
 
5236
4590
class cmd_bind(Command):
5237
 
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
5238
 
    If no branch is supplied, rebind to the last bound location.
 
4591
    """Convert the current branch into a checkout of the supplied branch.
5239
4592
 
5240
4593
    Once converted into a checkout, commits must succeed on the master branch
5241
4594
    before they will be applied to the local branch.
5247
4600
 
5248
4601
    _see_also = ['checkouts', 'unbind']
5249
4602
    takes_args = ['location?']
5250
 
    takes_options = ['directory']
 
4603
    takes_options = []
5251
4604
 
5252
 
    def run(self, location=None, directory=u'.'):
5253
 
        b, relpath = Branch.open_containing(directory)
 
4605
    def run(self, location=None):
 
4606
        b, relpath = Branch.open_containing(u'.')
5254
4607
        if location is None:
5255
4608
            try:
5256
4609
                location = b.get_old_bound_location()
5257
4610
            except errors.UpgradeRequired:
5258
 
                raise errors.BzrCommandError(gettext('No location supplied.  '
5259
 
                    'This format does not remember old locations.'))
 
4611
                raise errors.BzrCommandError('No location supplied.  '
 
4612
                    'This format does not remember old locations.')
5260
4613
            else:
5261
4614
                if location is None:
5262
 
                    if b.get_bound_location() is not None:
5263
 
                        raise errors.BzrCommandError(gettext('Branch is already bound'))
5264
 
                    else:
5265
 
                        raise errors.BzrCommandError(gettext('No location supplied '
5266
 
                            'and no previous location known'))
 
4615
                    raise errors.BzrCommandError('No location supplied and no '
 
4616
                        'previous location known')
5267
4617
        b_other = Branch.open(location)
5268
4618
        try:
5269
4619
            b.bind(b_other)
5270
4620
        except errors.DivergedBranches:
5271
 
            raise errors.BzrCommandError(gettext('These branches have diverged.'
5272
 
                                         ' Try merging, and then bind again.'))
 
4621
            raise errors.BzrCommandError('These branches have diverged.'
 
4622
                                         ' Try merging, and then bind again.')
5273
4623
        if b.get_config().has_explicit_nickname():
5274
4624
            b.nick = b_other.nick
5275
4625
 
5276
4626
 
5277
4627
class cmd_unbind(Command):
5278
 
    __doc__ = """Convert the current checkout into a regular branch.
 
4628
    """Convert the current checkout into a regular branch.
5279
4629
 
5280
4630
    After unbinding, the local branch is considered independent and subsequent
5281
4631
    commits will be local only.
5283
4633
 
5284
4634
    _see_also = ['checkouts', 'bind']
5285
4635
    takes_args = []
5286
 
    takes_options = ['directory']
 
4636
    takes_options = []
5287
4637
 
5288
 
    def run(self, directory=u'.'):
5289
 
        b, relpath = Branch.open_containing(directory)
 
4638
    def run(self):
 
4639
        b, relpath = Branch.open_containing(u'.')
5290
4640
        if not b.unbind():
5291
 
            raise errors.BzrCommandError(gettext('Local branch is not bound'))
 
4641
            raise errors.BzrCommandError('Local branch is not bound')
5292
4642
 
5293
4643
 
5294
4644
class cmd_uncommit(Command):
5295
 
    __doc__ = """Remove the last committed revision.
 
4645
    """Remove the last committed revision.
5296
4646
 
5297
4647
    --verbose will print out what is being removed.
5298
4648
    --dry-run will go through all the motions, but not actually
5315
4665
    takes_options = ['verbose', 'revision',
5316
4666
                    Option('dry-run', help='Don\'t actually make changes.'),
5317
4667
                    Option('force', help='Say yes to all questions.'),
5318
 
                    Option('keep-tags',
5319
 
                           help='Keep tags that point to removed revisions.'),
5320
4668
                    Option('local',
5321
4669
                           help="Only remove the commits from the local branch"
5322
4670
                                " when in a checkout."
5326
4674
    aliases = []
5327
4675
    encoding_type = 'replace'
5328
4676
 
5329
 
    def run(self, location=None, dry_run=False, verbose=False,
5330
 
            revision=None, force=False, local=False, keep_tags=False):
 
4677
    def run(self, location=None,
 
4678
            dry_run=False, verbose=False,
 
4679
            revision=None, force=False, local=False):
5331
4680
        if location is None:
5332
4681
            location = u'.'
5333
 
        control, relpath = controldir.ControlDir.open_containing(location)
 
4682
        control, relpath = bzrdir.BzrDir.open_containing(location)
5334
4683
        try:
5335
4684
            tree = control.open_workingtree()
5336
4685
            b = tree.branch
5339
4688
            b = control.open_branch()
5340
4689
 
5341
4690
        if tree is not None:
5342
 
            self.add_cleanup(tree.lock_write().unlock)
 
4691
            tree.lock_write()
 
4692
            self.add_cleanup(tree.unlock)
5343
4693
        else:
5344
 
            self.add_cleanup(b.lock_write().unlock)
5345
 
        return self._run(b, tree, dry_run, verbose, revision, force,
5346
 
                         local, keep_tags)
 
4694
            b.lock_write()
 
4695
            self.add_cleanup(b.unlock)
 
4696
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
5347
4697
 
5348
 
    def _run(self, b, tree, dry_run, verbose, revision, force, local,
5349
 
             keep_tags):
 
4698
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
5350
4699
        from bzrlib.log import log_formatter, show_log
5351
4700
        from bzrlib.uncommit import uncommit
5352
4701
 
5367
4716
                rev_id = b.get_rev_id(revno)
5368
4717
 
5369
4718
        if rev_id is None or _mod_revision.is_null(rev_id):
5370
 
            self.outf.write(gettext('No revisions to uncommit.\n'))
 
4719
            self.outf.write('No revisions to uncommit.\n')
5371
4720
            return 1
5372
4721
 
5373
4722
        lf = log_formatter('short',
5382
4731
                 end_revision=last_revno)
5383
4732
 
5384
4733
        if dry_run:
5385
 
            self.outf.write(gettext('Dry-run, pretending to remove'
5386
 
                            ' the above revisions.\n'))
 
4734
            print 'Dry-run, pretending to remove the above revisions.'
 
4735
            if not force:
 
4736
                val = raw_input('Press <enter> to continue')
5387
4737
        else:
5388
 
            self.outf.write(gettext('The above revision(s) will be removed.\n'))
5389
 
 
5390
 
        if not force:
5391
 
            if not ui.ui_factory.confirm_action(
5392
 
                    gettext(u'Uncommit these revisions'),
5393
 
                    'bzrlib.builtins.uncommit',
5394
 
                    {}):
5395
 
                self.outf.write(gettext('Canceled\n'))
5396
 
                return 0
 
4738
            print 'The above revision(s) will be removed.'
 
4739
            if not force:
 
4740
                val = raw_input('Are you sure [y/N]? ')
 
4741
                if val.lower() not in ('y', 'yes'):
 
4742
                    print 'Canceled'
 
4743
                    return 0
5397
4744
 
5398
4745
        mutter('Uncommitting from {%s} to {%s}',
5399
4746
               last_rev_id, rev_id)
5400
4747
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
5401
 
                 revno=revno, local=local, keep_tags=keep_tags)
5402
 
        self.outf.write(gettext('You can restore the old tip by running:\n'
5403
 
             '  bzr pull . -r revid:%s\n') % last_rev_id)
 
4748
                 revno=revno, local=local)
 
4749
        note('You can restore the old tip by running:\n'
 
4750
             '  bzr pull . -r revid:%s', last_rev_id)
5404
4751
 
5405
4752
 
5406
4753
class cmd_break_lock(Command):
5407
 
    __doc__ = """Break a dead lock.
5408
 
 
5409
 
    This command breaks a lock on a repository, branch, working directory or
5410
 
    config file.
 
4754
    """Break a dead lock on a repository, branch or working directory.
5411
4755
 
5412
4756
    CAUTION: Locks should only be broken when you are sure that the process
5413
4757
    holding the lock has been stopped.
5418
4762
    :Examples:
5419
4763
        bzr break-lock
5420
4764
        bzr break-lock bzr+ssh://example.com/bzr/foo
5421
 
        bzr break-lock --conf ~/.bazaar
5422
4765
    """
5423
 
 
5424
4766
    takes_args = ['location?']
5425
 
    takes_options = [
5426
 
        Option('config',
5427
 
               help='LOCATION is the directory where the config lock is.'),
5428
 
        Option('force',
5429
 
            help='Do not ask for confirmation before breaking the lock.'),
5430
 
        ]
5431
4767
 
5432
 
    def run(self, location=None, config=False, force=False):
 
4768
    def run(self, location=None, show=False):
5433
4769
        if location is None:
5434
4770
            location = u'.'
5435
 
        if force:
5436
 
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5437
 
                None,
5438
 
                {'bzrlib.lockdir.break': True})
5439
 
        if config:
5440
 
            conf = _mod_config.LockableConfig(file_name=location)
5441
 
            conf.break_lock()
5442
 
        else:
5443
 
            control, relpath = controldir.ControlDir.open_containing(location)
5444
 
            try:
5445
 
                control.break_lock()
5446
 
            except NotImplementedError:
5447
 
                pass
 
4771
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4772
        try:
 
4773
            control.break_lock()
 
4774
        except NotImplementedError:
 
4775
            pass
5448
4776
 
5449
4777
 
5450
4778
class cmd_wait_until_signalled(Command):
5451
 
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4779
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
5452
4780
 
5453
4781
    This just prints a line to signal when it is ready, then blocks on stdin.
5454
4782
    """
5462
4790
 
5463
4791
 
5464
4792
class cmd_serve(Command):
5465
 
    __doc__ = """Run the bzr server."""
 
4793
    """Run the bzr server."""
5466
4794
 
5467
4795
    aliases = ['server']
5468
4796
 
5479
4807
                    'result in a dynamically allocated port.  The default port '
5480
4808
                    'depends on the protocol.',
5481
4809
               type=str),
5482
 
        custom_help('directory',
5483
 
               help='Serve contents of this directory.'),
 
4810
        Option('directory',
 
4811
               help='Serve contents of this directory.',
 
4812
               type=unicode),
5484
4813
        Option('allow-writes',
5485
4814
               help='By default the server is a readonly server.  Supplying '
5486
4815
                    '--allow-writes enables write access to the contents of '
5490
4819
                    'option leads to global uncontrolled write access to your '
5491
4820
                    'file system.'
5492
4821
                ),
5493
 
        Option('client-timeout', type=float,
5494
 
               help='Override the default idle client timeout (5min).'),
5495
4822
        ]
5496
4823
 
5497
4824
    def get_host_and_port(self, port):
5514
4841
        return host, port
5515
4842
 
5516
4843
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
5517
 
            protocol=None, client_timeout=None):
5518
 
        from bzrlib import transport
 
4844
            protocol=None):
 
4845
        from bzrlib.transport import get_transport, transport_server_registry
5519
4846
        if directory is None:
5520
4847
            directory = os.getcwd()
5521
4848
        if protocol is None:
5522
 
            protocol = transport.transport_server_registry.get()
 
4849
            protocol = transport_server_registry.get()
5523
4850
        host, port = self.get_host_and_port(port)
5524
 
        url = transport.location_to_url(directory)
 
4851
        url = urlutils.local_path_to_url(directory)
5525
4852
        if not allow_writes:
5526
4853
            url = 'readonly+' + url
5527
 
        t = transport.get_transport_from_url(url)
5528
 
        try:
5529
 
            protocol(t, host, port, inet, client_timeout)
5530
 
        except TypeError, e:
5531
 
            # We use symbol_versioning.deprecated_in just so that people
5532
 
            # grepping can find it here.
5533
 
            # symbol_versioning.deprecated_in((2, 5, 0))
5534
 
            symbol_versioning.warn(
5535
 
                'Got TypeError(%s)\ntrying to call protocol: %s.%s\n'
5536
 
                'Most likely it needs to be updated to support a'
5537
 
                ' "timeout" parameter (added in bzr 2.5.0)'
5538
 
                % (e, protocol.__module__, protocol),
5539
 
                DeprecationWarning)
5540
 
            protocol(t, host, port, inet)
 
4854
        transport = get_transport(url)
 
4855
        protocol(transport, host, port, inet)
5541
4856
 
5542
4857
 
5543
4858
class cmd_join(Command):
5544
 
    __doc__ = """Combine a tree into its containing tree.
 
4859
    """Combine a tree into its containing tree.
5545
4860
 
5546
4861
    This command requires the target tree to be in a rich-root format.
5547
4862
 
5549
4864
    not part of it.  (Such trees can be produced by "bzr split", but also by
5550
4865
    running "bzr branch" with the target inside a tree.)
5551
4866
 
5552
 
    The result is a combined tree, with the subtree no longer an independent
 
4867
    The result is a combined tree, with the subtree no longer an independant
5553
4868
    part.  This is marked as a merge of the subtree into the containing tree,
5554
4869
    and all history is preserved.
5555
4870
    """
5566
4881
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
5567
4882
        repo = containing_tree.branch.repository
5568
4883
        if not repo.supports_rich_root():
5569
 
            raise errors.BzrCommandError(gettext(
 
4884
            raise errors.BzrCommandError(
5570
4885
                "Can't join trees because %s doesn't support rich root data.\n"
5571
 
                "You can use bzr upgrade on the repository.")
 
4886
                "You can use bzr upgrade on the repository."
5572
4887
                % (repo,))
5573
4888
        if reference:
5574
4889
            try:
5576
4891
            except errors.BadReferenceTarget, e:
5577
4892
                # XXX: Would be better to just raise a nicely printable
5578
4893
                # exception from the real origin.  Also below.  mbp 20070306
5579
 
                raise errors.BzrCommandError(
5580
 
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
4894
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
4895
                                             (tree, e.reason))
5581
4896
        else:
5582
4897
            try:
5583
4898
                containing_tree.subsume(sub_tree)
5584
4899
            except errors.BadSubsumeSource, e:
5585
 
                raise errors.BzrCommandError(
5586
 
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
4900
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
4901
                                             (tree, e.reason))
5587
4902
 
5588
4903
 
5589
4904
class cmd_split(Command):
5590
 
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
4905
    """Split a subdirectory of a tree into a separate tree.
5591
4906
 
5592
4907
    This command will produce a target tree in a format that supports
5593
4908
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
5613
4928
 
5614
4929
 
5615
4930
class cmd_merge_directive(Command):
5616
 
    __doc__ = """Generate a merge directive for auto-merge tools.
 
4931
    """Generate a merge directive for auto-merge tools.
5617
4932
 
5618
4933
    A directive requests a merge to be performed, and also provides all the
5619
4934
    information necessary to do so.  This means it must either include a
5636
4951
    _see_also = ['send']
5637
4952
 
5638
4953
    takes_options = [
5639
 
        'directory',
5640
4954
        RegistryOption.from_kwargs('patch-type',
5641
4955
            'The type of patch to include in the directive.',
5642
4956
            title='Patch type',
5655
4969
    encoding_type = 'exact'
5656
4970
 
5657
4971
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5658
 
            sign=False, revision=None, mail_to=None, message=None,
5659
 
            directory=u'.'):
 
4972
            sign=False, revision=None, mail_to=None, message=None):
5660
4973
        from bzrlib.revision import ensure_null, NULL_REVISION
5661
4974
        include_patch, include_bundle = {
5662
4975
            'plain': (False, False),
5663
4976
            'diff': (True, False),
5664
4977
            'bundle': (True, True),
5665
4978
            }[patch_type]
5666
 
        branch = Branch.open(directory)
 
4979
        branch = Branch.open('.')
5667
4980
        stored_submit_branch = branch.get_submit_branch()
5668
4981
        if submit_branch is None:
5669
4982
            submit_branch = stored_submit_branch
5673
4986
        if submit_branch is None:
5674
4987
            submit_branch = branch.get_parent()
5675
4988
        if submit_branch is None:
5676
 
            raise errors.BzrCommandError(gettext('No submit branch specified or known'))
 
4989
            raise errors.BzrCommandError('No submit branch specified or known')
5677
4990
 
5678
4991
        stored_public_branch = branch.get_public_branch()
5679
4992
        if public_branch is None:
5681
4994
        elif stored_public_branch is None:
5682
4995
            branch.set_public_branch(public_branch)
5683
4996
        if not include_bundle and public_branch is None:
5684
 
            raise errors.BzrCommandError(gettext('No public branch specified or'
5685
 
                                         ' known'))
 
4997
            raise errors.BzrCommandError('No public branch specified or'
 
4998
                                         ' known')
5686
4999
        base_revision_id = None
5687
5000
        if revision is not None:
5688
5001
            if len(revision) > 2:
5689
 
                raise errors.BzrCommandError(gettext('bzr merge-directive takes '
5690
 
                    'at most two one revision identifiers'))
 
5002
                raise errors.BzrCommandError('bzr merge-directive takes '
 
5003
                    'at most two one revision identifiers')
5691
5004
            revision_id = revision[-1].as_revision_id(branch)
5692
5005
            if len(revision) == 2:
5693
5006
                base_revision_id = revision[0].as_revision_id(branch)
5695
5008
            revision_id = branch.last_revision()
5696
5009
        revision_id = ensure_null(revision_id)
5697
5010
        if revision_id == NULL_REVISION:
5698
 
            raise errors.BzrCommandError(gettext('No revisions to bundle.'))
 
5011
            raise errors.BzrCommandError('No revisions to bundle.')
5699
5012
        directive = merge_directive.MergeDirective2.from_objects(
5700
5013
            branch.repository, revision_id, time.time(),
5701
5014
            osutils.local_time_offset(), submit_branch,
5709
5022
                self.outf.writelines(directive.to_lines())
5710
5023
        else:
5711
5024
            message = directive.to_email(mail_to, branch, sign)
5712
 
            s = SMTPConnection(branch.get_config_stack())
 
5025
            s = SMTPConnection(branch.get_config())
5713
5026
            s.send_email(message)
5714
5027
 
5715
5028
 
5716
5029
class cmd_send(Command):
5717
 
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
5030
    """Mail or create a merge-directive for submitting changes.
5718
5031
 
5719
5032
    A merge directive provides many things needed for requesting merges:
5720
5033
 
5745
5058
    source branch defaults to that containing the working directory, but can
5746
5059
    be changed using --from.
5747
5060
 
5748
 
    Both the submit branch and the public branch follow the usual behavior with
5749
 
    respect to --remember: If there is no default location set, the first send
5750
 
    will set it (use --no-remember to avoid setting it). After that, you can
5751
 
    omit the location to use the default.  To change the default, use
5752
 
    --remember. The value will only be saved if the location can be accessed.
5753
 
 
5754
5061
    In order to calculate those changes, bzr must analyse the submit branch.
5755
5062
    Therefore it is most efficient for the submit branch to be a local mirror.
5756
5063
    If a public location is known for the submit_branch, that location is used
5760
5067
    given, in which case it is sent to a file.
5761
5068
 
5762
5069
    Mail is sent using your preferred mail program.  This should be transparent
5763
 
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
5070
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
5764
5071
    If the preferred client can't be found (or used), your editor will be used.
5765
5072
 
5766
5073
    To use a specific mail program, set the mail_client configuration option.
5808
5115
               short_name='f',
5809
5116
               type=unicode),
5810
5117
        Option('output', short_name='o',
5811
 
               help='Write merge directive to this file or directory; '
 
5118
               help='Write merge directive to this file; '
5812
5119
                    'use - for stdout.',
5813
5120
               type=unicode),
5814
5121
        Option('strict',
5825
5132
        ]
5826
5133
 
5827
5134
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5828
 
            no_patch=False, revision=None, remember=None, output=None,
 
5135
            no_patch=False, revision=None, remember=False, output=None,
5829
5136
            format=None, mail_to=None, message=None, body=None,
5830
5137
            strict=None, **kwargs):
5831
5138
        from bzrlib.send import send
5837
5144
 
5838
5145
 
5839
5146
class cmd_bundle_revisions(cmd_send):
5840
 
    __doc__ = """Create a merge-directive for submitting changes.
 
5147
    """Create a merge-directive for submitting changes.
5841
5148
 
5842
5149
    A merge directive provides many things needed for requesting merges:
5843
5150
 
5910
5217
 
5911
5218
 
5912
5219
class cmd_tag(Command):
5913
 
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5220
    """Create, remove or modify a tag naming a revision.
5914
5221
 
5915
5222
    Tags give human-meaningful names to revisions.  Commands that take a -r
5916
5223
    (--revision) option can be given -rtag:X, where X is any previously
5924
5231
 
5925
5232
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
5926
5233
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5927
 
 
5928
 
    If no tag name is specified it will be determined through the 
5929
 
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
5930
 
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
5931
 
    details.
5932
5234
    """
5933
5235
 
5934
5236
    _see_also = ['commit', 'tags']
5935
 
    takes_args = ['tag_name?']
 
5237
    takes_args = ['tag_name']
5936
5238
    takes_options = [
5937
5239
        Option('delete',
5938
5240
            help='Delete this tag rather than placing it.',
5939
5241
            ),
5940
 
        custom_help('directory',
5941
 
            help='Branch in which to place the tag.'),
 
5242
        Option('directory',
 
5243
            help='Branch in which to place the tag.',
 
5244
            short_name='d',
 
5245
            type=unicode,
 
5246
            ),
5942
5247
        Option('force',
5943
5248
            help='Replace existing tags.',
5944
5249
            ),
5945
5250
        'revision',
5946
5251
        ]
5947
5252
 
5948
 
    def run(self, tag_name=None,
 
5253
    def run(self, tag_name,
5949
5254
            delete=None,
5950
5255
            directory='.',
5951
5256
            force=None,
5952
5257
            revision=None,
5953
5258
            ):
5954
5259
        branch, relpath = Branch.open_containing(directory)
5955
 
        self.add_cleanup(branch.lock_write().unlock)
 
5260
        branch.lock_write()
 
5261
        self.add_cleanup(branch.unlock)
5956
5262
        if delete:
5957
 
            if tag_name is None:
5958
 
                raise errors.BzrCommandError(gettext("No tag specified to delete."))
5959
5263
            branch.tags.delete_tag(tag_name)
5960
 
            note(gettext('Deleted tag %s.') % tag_name)
 
5264
            self.outf.write('Deleted tag %s.\n' % tag_name)
5961
5265
        else:
5962
5266
            if revision:
5963
5267
                if len(revision) != 1:
5964
 
                    raise errors.BzrCommandError(gettext(
 
5268
                    raise errors.BzrCommandError(
5965
5269
                        "Tags can only be placed on a single revision, "
5966
 
                        "not on a range"))
 
5270
                        "not on a range")
5967
5271
                revision_id = revision[0].as_revision_id(branch)
5968
5272
            else:
5969
5273
                revision_id = branch.last_revision()
5970
 
            if tag_name is None:
5971
 
                tag_name = branch.automatic_tag_name(revision_id)
5972
 
                if tag_name is None:
5973
 
                    raise errors.BzrCommandError(gettext(
5974
 
                        "Please specify a tag name."))
5975
 
            try:
5976
 
                existing_target = branch.tags.lookup_tag(tag_name)
5977
 
            except errors.NoSuchTag:
5978
 
                existing_target = None
5979
 
            if not force and existing_target not in (None, revision_id):
 
5274
            if (not force) and branch.tags.has_tag(tag_name):
5980
5275
                raise errors.TagAlreadyExists(tag_name)
5981
 
            if existing_target == revision_id:
5982
 
                note(gettext('Tag %s already exists for that revision.') % tag_name)
5983
 
            else:
5984
 
                branch.tags.set_tag(tag_name, revision_id)
5985
 
                if existing_target is None:
5986
 
                    note(gettext('Created tag %s.') % tag_name)
5987
 
                else:
5988
 
                    note(gettext('Updated tag %s.') % tag_name)
 
5276
            branch.tags.set_tag(tag_name, revision_id)
 
5277
            self.outf.write('Created tag %s.\n' % tag_name)
5989
5278
 
5990
5279
 
5991
5280
class cmd_tags(Command):
5992
 
    __doc__ = """List tags.
 
5281
    """List tags.
5993
5282
 
5994
5283
    This command shows a table of tag names and the revisions they reference.
5995
5284
    """
5996
5285
 
5997
5286
    _see_also = ['tag']
5998
5287
    takes_options = [
5999
 
        custom_help('directory',
6000
 
            help='Branch whose tags should be displayed.'),
6001
 
        RegistryOption('sort',
 
5288
        Option('directory',
 
5289
            help='Branch whose tags should be displayed.',
 
5290
            short_name='d',
 
5291
            type=unicode,
 
5292
            ),
 
5293
        RegistryOption.from_kwargs('sort',
6002
5294
            'Sort tags by different criteria.', title='Sorting',
6003
 
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
 
5295
            alpha='Sort tags lexicographically (default).',
 
5296
            time='Sort tags chronologically.',
6004
5297
            ),
6005
5298
        'show-ids',
6006
5299
        'revision',
6007
5300
    ]
6008
5301
 
6009
5302
    @display_command
6010
 
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
6011
 
        from bzrlib.tag import tag_sort_methods
 
5303
    def run(self,
 
5304
            directory='.',
 
5305
            sort='alpha',
 
5306
            show_ids=False,
 
5307
            revision=None,
 
5308
            ):
6012
5309
        branch, relpath = Branch.open_containing(directory)
6013
5310
 
6014
5311
        tags = branch.tags.get_tag_dict().items()
6015
5312
        if not tags:
6016
5313
            return
6017
5314
 
6018
 
        self.add_cleanup(branch.lock_read().unlock)
 
5315
        branch.lock_read()
 
5316
        self.add_cleanup(branch.unlock)
6019
5317
        if revision:
6020
 
            # Restrict to the specified range
6021
 
            tags = self._tags_for_range(branch, revision)
6022
 
        if sort is None:
6023
 
            sort = tag_sort_methods.get()
6024
 
        sort(branch, tags)
 
5318
            graph = branch.repository.get_graph()
 
5319
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5320
            revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5321
            # only show revisions between revid1 and revid2 (inclusive)
 
5322
            tags = [(tag, revid) for tag, revid in tags if
 
5323
                graph.is_between(revid, revid1, revid2)]
 
5324
        if sort == 'alpha':
 
5325
            tags.sort()
 
5326
        elif sort == 'time':
 
5327
            timestamps = {}
 
5328
            for tag, revid in tags:
 
5329
                try:
 
5330
                    revobj = branch.repository.get_revision(revid)
 
5331
                except errors.NoSuchRevision:
 
5332
                    timestamp = sys.maxint # place them at the end
 
5333
                else:
 
5334
                    timestamp = revobj.timestamp
 
5335
                timestamps[revid] = timestamp
 
5336
            tags.sort(key=lambda x: timestamps[x[1]])
6025
5337
        if not show_ids:
6026
5338
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
6027
5339
            for index, (tag, revid) in enumerate(tags):
6029
5341
                    revno = branch.revision_id_to_dotted_revno(revid)
6030
5342
                    if isinstance(revno, tuple):
6031
5343
                        revno = '.'.join(map(str, revno))
6032
 
                except (errors.NoSuchRevision,
6033
 
                        errors.GhostRevisionsHaveNoRevno,
6034
 
                        errors.UnsupportedOperation):
 
5344
                except errors.NoSuchRevision:
6035
5345
                    # Bad tag data/merges can lead to tagged revisions
6036
5346
                    # which are not in this branch. Fail gracefully ...
6037
5347
                    revno = '?'
6040
5350
        for tag, revspec in tags:
6041
5351
            self.outf.write('%-20s %s\n' % (tag, revspec))
6042
5352
 
6043
 
    def _tags_for_range(self, branch, revision):
6044
 
        range_valid = True
6045
 
        rev1, rev2 = _get_revision_range(revision, branch, self.name())
6046
 
        revid1, revid2 = rev1.rev_id, rev2.rev_id
6047
 
        # _get_revision_range will always set revid2 if it's not specified.
6048
 
        # If revid1 is None, it means we want to start from the branch
6049
 
        # origin which is always a valid ancestor. If revid1 == revid2, the
6050
 
        # ancestry check is useless.
6051
 
        if revid1 and revid1 != revid2:
6052
 
            # FIXME: We really want to use the same graph than
6053
 
            # branch.iter_merge_sorted_revisions below, but this is not
6054
 
            # easily available -- vila 2011-09-23
6055
 
            if branch.repository.get_graph().is_ancestor(revid2, revid1):
6056
 
                # We don't want to output anything in this case...
6057
 
                return []
6058
 
        # only show revisions between revid1 and revid2 (inclusive)
6059
 
        tagged_revids = branch.tags.get_reverse_tag_dict()
6060
 
        found = []
6061
 
        for r in branch.iter_merge_sorted_revisions(
6062
 
            start_revision_id=revid2, stop_revision_id=revid1,
6063
 
            stop_rule='include'):
6064
 
            revid_tags = tagged_revids.get(r[0], None)
6065
 
            if revid_tags:
6066
 
                found.extend([(tag, r[0]) for tag in revid_tags])
6067
 
        return found
6068
 
 
6069
5353
 
6070
5354
class cmd_reconfigure(Command):
6071
 
    __doc__ = """Reconfigure the type of a bzr directory.
 
5355
    """Reconfigure the type of a bzr directory.
6072
5356
 
6073
5357
    A target configuration must be specified.
6074
5358
 
6085
5369
    takes_args = ['location?']
6086
5370
    takes_options = [
6087
5371
        RegistryOption.from_kwargs(
6088
 
            'tree_type',
6089
 
            title='Tree type',
6090
 
            help='The relation between branch and tree.',
 
5372
            'target_type',
 
5373
            title='Target type',
 
5374
            help='The type to reconfigure the directory to.',
6091
5375
            value_switches=True, enum_switch=False,
6092
5376
            branch='Reconfigure to be an unbound branch with no working tree.',
6093
5377
            tree='Reconfigure to be an unbound branch with a working tree.',
6094
5378
            checkout='Reconfigure to be a bound branch with a working tree.',
6095
5379
            lightweight_checkout='Reconfigure to be a lightweight'
6096
5380
                ' checkout (with no local history).',
6097
 
            ),
6098
 
        RegistryOption.from_kwargs(
6099
 
            'repository_type',
6100
 
            title='Repository type',
6101
 
            help='Location fo the repository.',
6102
 
            value_switches=True, enum_switch=False,
6103
5381
            standalone='Reconfigure to be a standalone branch '
6104
5382
                '(i.e. stop using shared repository).',
6105
5383
            use_shared='Reconfigure to use a shared repository.',
6106
 
            ),
6107
 
        RegistryOption.from_kwargs(
6108
 
            'repository_trees',
6109
 
            title='Trees in Repository',
6110
 
            help='Whether new branches in the repository have trees.',
6111
 
            value_switches=True, enum_switch=False,
6112
5384
            with_trees='Reconfigure repository to create '
6113
5385
                'working trees on branches by default.',
6114
5386
            with_no_trees='Reconfigure repository to not create '
6128
5400
            ),
6129
5401
        ]
6130
5402
 
6131
 
    def run(self, location=None, bind_to=None, force=False,
6132
 
            tree_type=None, repository_type=None, repository_trees=None,
6133
 
            stacked_on=None, unstacked=None):
6134
 
        directory = controldir.ControlDir.open(location)
 
5403
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5404
            stacked_on=None,
 
5405
            unstacked=None):
 
5406
        directory = bzrdir.BzrDir.open(location)
6135
5407
        if stacked_on and unstacked:
6136
 
            raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
 
5408
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
6137
5409
        elif stacked_on is not None:
6138
5410
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
6139
5411
        elif unstacked:
6141
5413
        # At the moment you can use --stacked-on and a different
6142
5414
        # reconfiguration shape at the same time; there seems no good reason
6143
5415
        # to ban it.
6144
 
        if (tree_type is None and
6145
 
            repository_type is None and
6146
 
            repository_trees is None):
 
5416
        if target_type is None:
6147
5417
            if stacked_on or unstacked:
6148
5418
                return
6149
5419
            else:
6150
 
                raise errors.BzrCommandError(gettext('No target configuration '
6151
 
                    'specified'))
6152
 
        reconfiguration = None
6153
 
        if tree_type == 'branch':
 
5420
                raise errors.BzrCommandError('No target configuration '
 
5421
                    'specified')
 
5422
        elif target_type == 'branch':
6154
5423
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
6155
 
        elif tree_type == 'tree':
 
5424
        elif target_type == 'tree':
6156
5425
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
6157
 
        elif tree_type == 'checkout':
 
5426
        elif target_type == 'checkout':
6158
5427
            reconfiguration = reconfigure.Reconfigure.to_checkout(
6159
5428
                directory, bind_to)
6160
 
        elif tree_type == 'lightweight-checkout':
 
5429
        elif target_type == 'lightweight-checkout':
6161
5430
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
6162
5431
                directory, bind_to)
6163
 
        if reconfiguration:
6164
 
            reconfiguration.apply(force)
6165
 
            reconfiguration = None
6166
 
        if repository_type == 'use-shared':
 
5432
        elif target_type == 'use-shared':
6167
5433
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
6168
 
        elif repository_type == 'standalone':
 
5434
        elif target_type == 'standalone':
6169
5435
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
6170
 
        if reconfiguration:
6171
 
            reconfiguration.apply(force)
6172
 
            reconfiguration = None
6173
 
        if repository_trees == 'with-trees':
 
5436
        elif target_type == 'with-trees':
6174
5437
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6175
5438
                directory, True)
6176
 
        elif repository_trees == 'with-no-trees':
 
5439
        elif target_type == 'with-no-trees':
6177
5440
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6178
5441
                directory, False)
6179
 
        if reconfiguration:
6180
 
            reconfiguration.apply(force)
6181
 
            reconfiguration = None
 
5442
        reconfiguration.apply(force)
6182
5443
 
6183
5444
 
6184
5445
class cmd_switch(Command):
6185
 
    __doc__ = """Set the branch of a checkout and update.
 
5446
    """Set the branch of a checkout and update.
6186
5447
 
6187
5448
    For lightweight checkouts, this changes the branch being referenced.
6188
5449
    For heavyweight checkouts, this checks that there are no local commits
6205
5466
    """
6206
5467
 
6207
5468
    takes_args = ['to_location?']
6208
 
    takes_options = ['directory',
6209
 
                     Option('force',
 
5469
    takes_options = [Option('force',
6210
5470
                        help='Switch even if local commits will be lost.'),
6211
5471
                     'revision',
6212
5472
                     Option('create-branch', short_name='b',
6215
5475
                    ]
6216
5476
 
6217
5477
    def run(self, to_location=None, force=False, create_branch=False,
6218
 
            revision=None, directory=u'.'):
 
5478
            revision=None):
6219
5479
        from bzrlib import switch
6220
 
        tree_location = directory
 
5480
        tree_location = '.'
6221
5481
        revision = _get_one_revision('switch', revision)
6222
 
        possible_transports = []
6223
 
        control_dir = controldir.ControlDir.open_containing(tree_location,
6224
 
            possible_transports=possible_transports)[0]
 
5482
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
6225
5483
        if to_location is None:
6226
5484
            if revision is None:
6227
 
                raise errors.BzrCommandError(gettext('You must supply either a'
6228
 
                                             ' revision or a location'))
6229
 
            to_location = tree_location
 
5485
                raise errors.BzrCommandError('You must supply either a'
 
5486
                                             ' revision or a location')
 
5487
            to_location = '.'
6230
5488
        try:
6231
 
            branch = control_dir.open_branch(
6232
 
                possible_transports=possible_transports)
 
5489
            branch = control_dir.open_branch()
6233
5490
            had_explicit_nick = branch.get_config().has_explicit_nickname()
6234
5491
        except errors.NotBranchError:
6235
5492
            branch = None
6236
5493
            had_explicit_nick = False
6237
5494
        if create_branch:
6238
5495
            if branch is None:
6239
 
                raise errors.BzrCommandError(
6240
 
                    gettext('cannot create branch without source branch'))
6241
 
            to_location = lookup_new_sibling_branch(control_dir, to_location,
6242
 
                 possible_transports=possible_transports)
 
5496
                raise errors.BzrCommandError('cannot create branch without'
 
5497
                                             ' source branch')
 
5498
            to_location = directory_service.directories.dereference(
 
5499
                              to_location)
 
5500
            if '/' not in to_location and '\\' not in to_location:
 
5501
                # This path is meant to be relative to the existing branch
 
5502
                this_url = self._get_branch_location(control_dir)
 
5503
                to_location = urlutils.join(this_url, '..', to_location)
6243
5504
            to_branch = branch.bzrdir.sprout(to_location,
6244
 
                 possible_transports=possible_transports,
6245
 
                 source_branch=branch).open_branch()
 
5505
                                 possible_transports=[branch.bzrdir.root_transport],
 
5506
                                 source_branch=branch).open_branch()
6246
5507
        else:
6247
 
            to_branch = lookup_sibling_branch(control_dir, to_location)
 
5508
            try:
 
5509
                to_branch = Branch.open(to_location)
 
5510
            except errors.NotBranchError:
 
5511
                this_url = self._get_branch_location(control_dir)
 
5512
                to_branch = Branch.open(
 
5513
                    urlutils.join(this_url, '..', to_location))
6248
5514
        if revision is not None:
6249
5515
            revision = revision.as_revision_id(to_branch)
6250
5516
        switch.switch(control_dir, to_branch, force, revision_id=revision)
6251
5517
        if had_explicit_nick:
6252
5518
            branch = control_dir.open_branch() #get the new branch!
6253
5519
            branch.nick = to_branch.nick
6254
 
        note(gettext('Switched to branch: %s'),
 
5520
        note('Switched to branch: %s',
6255
5521
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
6256
5522
 
 
5523
    def _get_branch_location(self, control_dir):
 
5524
        """Return location of branch for this control dir."""
 
5525
        try:
 
5526
            this_branch = control_dir.open_branch()
 
5527
            # This may be a heavy checkout, where we want the master branch
 
5528
            master_location = this_branch.get_bound_location()
 
5529
            if master_location is not None:
 
5530
                return master_location
 
5531
            # If not, use a local sibling
 
5532
            return this_branch.base
 
5533
        except errors.NotBranchError:
 
5534
            format = control_dir.find_branch_format()
 
5535
            if getattr(format, 'get_reference', None) is not None:
 
5536
                return format.get_reference(control_dir)
 
5537
            else:
 
5538
                return control_dir.root_transport.base
6257
5539
 
6258
5540
 
6259
5541
class cmd_view(Command):
6260
 
    __doc__ = """Manage filtered views.
 
5542
    """Manage filtered views.
6261
5543
 
6262
5544
    Views provide a mask over the tree so that users can focus on
6263
5545
    a subset of a tree when doing their work. After creating a view,
6343
5625
            name=None,
6344
5626
            switch=None,
6345
5627
            ):
6346
 
        tree, file_list = WorkingTree.open_containing_paths(file_list,
6347
 
            apply_view=False)
 
5628
        tree, file_list = tree_files(file_list, apply_view=False)
6348
5629
        current_view, view_dict = tree.views.get_view_info()
6349
5630
        if name is None:
6350
5631
            name = current_view
6351
5632
        if delete:
6352
5633
            if file_list:
6353
 
                raise errors.BzrCommandError(gettext(
6354
 
                    "Both --delete and a file list specified"))
 
5634
                raise errors.BzrCommandError(
 
5635
                    "Both --delete and a file list specified")
6355
5636
            elif switch:
6356
 
                raise errors.BzrCommandError(gettext(
6357
 
                    "Both --delete and --switch specified"))
 
5637
                raise errors.BzrCommandError(
 
5638
                    "Both --delete and --switch specified")
6358
5639
            elif all:
6359
5640
                tree.views.set_view_info(None, {})
6360
 
                self.outf.write(gettext("Deleted all views.\n"))
 
5641
                self.outf.write("Deleted all views.\n")
6361
5642
            elif name is None:
6362
 
                raise errors.BzrCommandError(gettext("No current view to delete"))
 
5643
                raise errors.BzrCommandError("No current view to delete")
6363
5644
            else:
6364
5645
                tree.views.delete_view(name)
6365
 
                self.outf.write(gettext("Deleted '%s' view.\n") % name)
 
5646
                self.outf.write("Deleted '%s' view.\n" % name)
6366
5647
        elif switch:
6367
5648
            if file_list:
6368
 
                raise errors.BzrCommandError(gettext(
6369
 
                    "Both --switch and a file list specified"))
 
5649
                raise errors.BzrCommandError(
 
5650
                    "Both --switch and a file list specified")
6370
5651
            elif all:
6371
 
                raise errors.BzrCommandError(gettext(
6372
 
                    "Both --switch and --all specified"))
 
5652
                raise errors.BzrCommandError(
 
5653
                    "Both --switch and --all specified")
6373
5654
            elif switch == 'off':
6374
5655
                if current_view is None:
6375
 
                    raise errors.BzrCommandError(gettext("No current view to disable"))
 
5656
                    raise errors.BzrCommandError("No current view to disable")
6376
5657
                tree.views.set_view_info(None, view_dict)
6377
 
                self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
 
5658
                self.outf.write("Disabled '%s' view.\n" % (current_view))
6378
5659
            else:
6379
5660
                tree.views.set_view_info(switch, view_dict)
6380
5661
                view_str = views.view_display_str(tree.views.lookup_view())
6381
 
                self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
 
5662
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
6382
5663
        elif all:
6383
5664
            if view_dict:
6384
 
                self.outf.write(gettext('Views defined:\n'))
 
5665
                self.outf.write('Views defined:\n')
6385
5666
                for view in sorted(view_dict):
6386
5667
                    if view == current_view:
6387
5668
                        active = "=>"
6390
5671
                    view_str = views.view_display_str(view_dict[view])
6391
5672
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
6392
5673
            else:
6393
 
                self.outf.write(gettext('No views defined.\n'))
 
5674
                self.outf.write('No views defined.\n')
6394
5675
        elif file_list:
6395
5676
            if name is None:
6396
5677
                # No name given and no current view set
6397
5678
                name = 'my'
6398
5679
            elif name == 'off':
6399
 
                raise errors.BzrCommandError(gettext(
6400
 
                    "Cannot change the 'off' pseudo view"))
 
5680
                raise errors.BzrCommandError(
 
5681
                    "Cannot change the 'off' pseudo view")
6401
5682
            tree.views.set_view(name, sorted(file_list))
6402
5683
            view_str = views.view_display_str(tree.views.lookup_view())
6403
 
            self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
 
5684
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
6404
5685
        else:
6405
5686
            # list the files
6406
5687
            if name is None:
6407
5688
                # No name given and no current view set
6408
 
                self.outf.write(gettext('No current view.\n'))
 
5689
                self.outf.write('No current view.\n')
6409
5690
            else:
6410
5691
                view_str = views.view_display_str(tree.views.lookup_view(name))
6411
 
                self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
 
5692
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
6412
5693
 
6413
5694
 
6414
5695
class cmd_hooks(Command):
6415
 
    __doc__ = """Show hooks."""
 
5696
    """Show hooks."""
6416
5697
 
6417
5698
    hidden = True
6418
5699
 
6428
5709
                        self.outf.write("    %s\n" %
6429
5710
                                        (some_hooks.get_hook_name(hook),))
6430
5711
                else:
6431
 
                    self.outf.write(gettext("    <no hooks installed>\n"))
6432
 
 
6433
 
 
6434
 
class cmd_remove_branch(Command):
6435
 
    __doc__ = """Remove a branch.
6436
 
 
6437
 
    This will remove the branch from the specified location but 
6438
 
    will keep any working tree or repository in place.
6439
 
 
6440
 
    :Examples:
6441
 
 
6442
 
      Remove the branch at repo/trunk::
6443
 
 
6444
 
        bzr remove-branch repo/trunk
6445
 
 
6446
 
    """
6447
 
 
6448
 
    takes_args = ["location?"]
6449
 
 
6450
 
    aliases = ["rmbranch"]
6451
 
 
6452
 
    def run(self, location=None):
6453
 
        if location is None:
6454
 
            location = "."
6455
 
        cdir = controldir.ControlDir.open_containing(location)[0]
6456
 
        cdir.destroy_branch()
 
5712
                    self.outf.write("    <no hooks installed>\n")
6457
5713
 
6458
5714
 
6459
5715
class cmd_shelve(Command):
6460
 
    __doc__ = """Temporarily set aside some changes from the current tree.
 
5716
    """Temporarily set aside some changes from the current tree.
6461
5717
 
6462
5718
    Shelve allows you to temporarily put changes you've made "on the shelf",
6463
5719
    ie. out of the way, until a later time when you can bring them back from
6479
5735
 
6480
5736
    You can put multiple items on the shelf, and by default, 'unshelve' will
6481
5737
    restore the most recently shelved changes.
6482
 
 
6483
 
    For complicated changes, it is possible to edit the changes in a separate
6484
 
    editor program to decide what the file remaining in the working copy
6485
 
    should look like.  To do this, add the configuration option
6486
 
 
6487
 
        change_editor = PROGRAM @new_path @old_path
6488
 
 
6489
 
    where @new_path is replaced with the path of the new version of the 
6490
 
    file and @old_path is replaced with the path of the old version of 
6491
 
    the file.  The PROGRAM should save the new file with the desired 
6492
 
    contents of the file in the working tree.
6493
 
        
6494
5738
    """
6495
5739
 
6496
5740
    takes_args = ['file*']
6497
5741
 
6498
5742
    takes_options = [
6499
 
        'directory',
6500
5743
        'revision',
6501
5744
        Option('all', help='Shelve all changes.'),
6502
5745
        'message',
6508
5751
        Option('destroy',
6509
5752
               help='Destroy removed changes instead of shelving them.'),
6510
5753
    ]
6511
 
    _see_also = ['unshelve', 'configuration']
 
5754
    _see_also = ['unshelve']
6512
5755
 
6513
5756
    def run(self, revision=None, all=False, file_list=None, message=None,
6514
 
            writer=None, list=False, destroy=False, directory=None):
 
5757
            writer=None, list=False, destroy=False):
6515
5758
        if list:
6516
 
            return self.run_for_list(directory=directory)
 
5759
            return self.run_for_list()
6517
5760
        from bzrlib.shelf_ui import Shelver
6518
5761
        if writer is None:
6519
5762
            writer = bzrlib.option.diff_writer_registry.get()
6520
5763
        try:
6521
5764
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6522
 
                file_list, message, destroy=destroy, directory=directory)
 
5765
                file_list, message, destroy=destroy)
6523
5766
            try:
6524
5767
                shelver.run()
6525
5768
            finally:
6527
5770
        except errors.UserAbort:
6528
5771
            return 0
6529
5772
 
6530
 
    def run_for_list(self, directory=None):
6531
 
        if directory is None:
6532
 
            directory = u'.'
6533
 
        tree = WorkingTree.open_containing(directory)[0]
6534
 
        self.add_cleanup(tree.lock_read().unlock)
 
5773
    def run_for_list(self):
 
5774
        tree = WorkingTree.open_containing('.')[0]
 
5775
        tree.lock_read()
 
5776
        self.add_cleanup(tree.unlock)
6535
5777
        manager = tree.get_shelf_manager()
6536
5778
        shelves = manager.active_shelves()
6537
5779
        if len(shelves) == 0:
6538
 
            note(gettext('No shelved changes.'))
 
5780
            note('No shelved changes.')
6539
5781
            return 0
6540
5782
        for shelf_id in reversed(shelves):
6541
5783
            message = manager.get_metadata(shelf_id).get('message')
6546
5788
 
6547
5789
 
6548
5790
class cmd_unshelve(Command):
6549
 
    __doc__ = """Restore shelved changes.
 
5791
    """Restore shelved changes.
6550
5792
 
6551
5793
    By default, the most recently shelved changes are restored. However if you
6552
5794
    specify a shelf by id those changes will be restored instead.  This works
6555
5797
 
6556
5798
    takes_args = ['shelf_id?']
6557
5799
    takes_options = [
6558
 
        'directory',
6559
5800
        RegistryOption.from_kwargs(
6560
5801
            'action', help="The action to perform.",
6561
5802
            enum_switch=False, value_switches=True,
6569
5810
    ]
6570
5811
    _see_also = ['shelve']
6571
5812
 
6572
 
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
5813
    def run(self, shelf_id=None, action='apply'):
6573
5814
        from bzrlib.shelf_ui import Unshelver
6574
 
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
5815
        unshelver = Unshelver.from_args(shelf_id, action)
6575
5816
        try:
6576
5817
            unshelver.run()
6577
5818
        finally:
6579
5820
 
6580
5821
 
6581
5822
class cmd_clean_tree(Command):
6582
 
    __doc__ = """Remove unwanted files from working tree.
 
5823
    """Remove unwanted files from working tree.
6583
5824
 
6584
5825
    By default, only unknown files, not ignored files, are deleted.  Versioned
6585
5826
    files are never deleted.
6593
5834
 
6594
5835
    To check what clean-tree will do, use --dry-run.
6595
5836
    """
6596
 
    takes_options = ['directory',
6597
 
                     Option('ignored', help='Delete all ignored files.'),
6598
 
                     Option('detritus', help='Delete conflict files, merge and revert'
 
5837
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5838
                     Option('detritus', help='Delete conflict files, merge'
6599
5839
                            ' backups, and failed selftest dirs.'),
6600
5840
                     Option('unknown',
6601
5841
                            help='Delete files unknown to bzr (default).'),
6603
5843
                            ' deleting them.'),
6604
5844
                     Option('force', help='Do not prompt before deleting.')]
6605
5845
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6606
 
            force=False, directory=u'.'):
 
5846
            force=False):
6607
5847
        from bzrlib.clean_tree import clean_tree
6608
5848
        if not (unknown or ignored or detritus):
6609
5849
            unknown = True
6610
5850
        if dry_run:
6611
5851
            force = True
6612
 
        clean_tree(directory, unknown=unknown, ignored=ignored,
6613
 
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5852
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5853
                   dry_run=dry_run, no_prompt=force)
6614
5854
 
6615
5855
 
6616
5856
class cmd_reference(Command):
6617
 
    __doc__ = """list, view and set branch locations for nested trees.
 
5857
    """list, view and set branch locations for nested trees.
6618
5858
 
6619
5859
    If no arguments are provided, lists the branch locations for nested trees.
6620
5860
    If one argument is provided, display the branch location for that tree.
6630
5870
        if path is not None:
6631
5871
            branchdir = path
6632
5872
        tree, branch, relpath =(
6633
 
            controldir.ControlDir.open_containing_tree_or_branch(branchdir))
 
5873
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6634
5874
        if path is not None:
6635
5875
            path = relpath
6636
5876
        if tree is None:
6660
5900
            self.outf.write('%s %s\n' % (path, location))
6661
5901
 
6662
5902
 
6663
 
class cmd_export_pot(Command):
6664
 
    __doc__ = """Export command helps and error messages in po format."""
6665
 
 
6666
 
    hidden = True
6667
 
    takes_options = [Option('plugin', 
6668
 
                            help='Export help text from named command '\
6669
 
                                 '(defaults to all built in commands).',
6670
 
                            type=str),
6671
 
                     Option('include-duplicates',
6672
 
                            help='Output multiple copies of the same msgid '
6673
 
                                 'string if it appears more than once.'),
6674
 
                            ]
6675
 
 
6676
 
    def run(self, plugin=None, include_duplicates=False):
6677
 
        from bzrlib.export_pot import export_pot
6678
 
        export_pot(self.outf, plugin, include_duplicates)
6679
 
 
6680
 
 
6681
 
def _register_lazy_builtins():
6682
 
    # register lazy builtins from other modules; called at startup and should
6683
 
    # be only called once.
6684
 
    for (name, aliases, module_name) in [
6685
 
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6686
 
        ('cmd_config', [], 'bzrlib.config'),
6687
 
        ('cmd_dpush', [], 'bzrlib.foreign'),
6688
 
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6689
 
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6690
 
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6691
 
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6692
 
        ('cmd_verify_signatures', [],
6693
 
                                        'bzrlib.commit_signature_commands'),
6694
 
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6695
 
        ]:
6696
 
        builtin_command_registry.register_lazy(name, aliases, module_name)
 
5903
# these get imported and then picked up by the scan for cmd_*
 
5904
# TODO: Some more consistent way to split command definitions across files;
 
5905
# we do need to load at least some information about them to know of
 
5906
# aliases.  ideally we would avoid loading the implementation until the
 
5907
# details were needed.
 
5908
from bzrlib.cmd_version_info import cmd_version_info
 
5909
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
5910
from bzrlib.bundle.commands import (
 
5911
    cmd_bundle_info,
 
5912
    )
 
5913
from bzrlib.foreign import cmd_dpush
 
5914
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
5915
from bzrlib.weave_commands import cmd_versionedfile_list, \
 
5916
        cmd_weave_plan_merge, cmd_weave_merge_text