/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/builtins.py

  • Committer: Martin
  • Date: 2017-06-18 10:15:11 UTC
  • mto: This revision was merged to the branch mainline in revision 6715.
  • Revision ID: gzlist@googlemail.com-20170618101511-fri1mouxt1hc09r8
Make _simple_set tests pass on py3 and with random hash

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2012 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""builtin brz commands"""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
import errno
 
22
import os
 
23
import sys
 
24
 
 
25
import breezy.bzr
 
26
 
 
27
from . import lazy_import
 
28
lazy_import.lazy_import(globals(), """
 
29
import time
 
30
 
 
31
import breezy
 
32
from breezy import (
 
33
    bugtracker,
 
34
    bundle,
 
35
    cache_utf8,
 
36
    controldir,
 
37
    directory_service,
 
38
    delta,
 
39
    config as _mod_config,
 
40
    errors,
 
41
    globbing,
 
42
    hooks,
 
43
    log,
 
44
    merge as _mod_merge,
 
45
    merge_directive,
 
46
    osutils,
 
47
    reconfigure,
 
48
    rename_map,
 
49
    revision as _mod_revision,
 
50
    static_tuple,
 
51
    symbol_versioning,
 
52
    timestamp,
 
53
    transport,
 
54
    ui,
 
55
    urlutils,
 
56
    views,
 
57
    gpg,
 
58
    )
 
59
from breezy.bzr import (
 
60
    btree_index,
 
61
    )
 
62
from breezy.branch import Branch
 
63
from breezy.conflicts import ConflictList
 
64
from breezy.transport import memory
 
65
from breezy.revisionspec import RevisionSpec, RevisionInfo
 
66
from breezy.smtp_connection import SMTPConnection
 
67
from breezy.workingtree import WorkingTree
 
68
from breezy.i18n import gettext, ngettext
 
69
""")
 
70
 
 
71
from .commands import (
 
72
    Command,
 
73
    builtin_command_registry,
 
74
    display_command,
 
75
    )
 
76
from .option import (
 
77
    ListOption,
 
78
    Option,
 
79
    RegistryOption,
 
80
    custom_help,
 
81
    _parse_revision_str,
 
82
    )
 
83
from .sixish import (
 
84
    BytesIO,
 
85
    text_type,
 
86
    viewitems,
 
87
    viewvalues,
 
88
)
 
89
from .trace import mutter, note, warning, is_quiet, get_verbosity_level
 
90
 
 
91
 
 
92
def _get_branch_location(control_dir, possible_transports=None):
 
93
    """Return location of branch for this control dir."""
 
94
    try:
 
95
        target = control_dir.get_branch_reference()
 
96
    except errors.NotBranchError:
 
97
        return control_dir.root_transport.base
 
98
    if target is not None:
 
99
        return target
 
100
    this_branch = control_dir.open_branch(
 
101
        possible_transports=possible_transports)
 
102
    # This may be a heavy checkout, where we want the master branch
 
103
    master_location = this_branch.get_bound_location()
 
104
    if master_location is not None:
 
105
        return master_location
 
106
    # If not, use a local sibling
 
107
    return this_branch.base
 
108
 
 
109
 
 
110
def _is_colocated(control_dir, possible_transports=None):
 
111
    """Check if the branch in control_dir is colocated.
 
112
 
 
113
    :param control_dir: Control directory
 
114
    :return: Tuple with boolean indicating whether the branch is colocated
 
115
        and the full URL to the actual branch
 
116
    """
 
117
    # This path is meant to be relative to the existing branch
 
118
    this_url = _get_branch_location(control_dir,
 
119
        possible_transports=possible_transports)
 
120
    # Perhaps the target control dir supports colocated branches?
 
121
    try:
 
122
        root = controldir.ControlDir.open(this_url,
 
123
            possible_transports=possible_transports)
 
124
    except errors.NotBranchError:
 
125
        return (False, this_url)
 
126
    else:
 
127
        try:
 
128
            wt = control_dir.open_workingtree()
 
129
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
130
            return (False, this_url)
 
131
        else:
 
132
            return (
 
133
                root._format.colocated_branches and
 
134
                control_dir.control_url == root.control_url,
 
135
                this_url)
 
136
 
 
137
 
 
138
def lookup_new_sibling_branch(control_dir, location, possible_transports=None):
 
139
    """Lookup the location for a new sibling branch.
 
140
 
 
141
    :param control_dir: Control directory to find sibling branches from
 
142
    :param location: Name of the new branch
 
143
    :return: Full location to the new branch
 
144
    """
 
145
    location = directory_service.directories.dereference(location)
 
146
    if '/' not in location and '\\' not in location:
 
147
        (colocated, this_url) = _is_colocated(control_dir, possible_transports)
 
148
 
 
149
        if colocated:
 
150
            return urlutils.join_segment_parameters(this_url,
 
151
                {"branch": urlutils.escape(location)})
 
152
        else:
 
153
            return urlutils.join(this_url, '..', urlutils.escape(location))
 
154
    return location
 
155
 
 
156
 
 
157
def open_sibling_branch(control_dir, location, possible_transports=None):
 
158
    """Open a branch, possibly a sibling of another.
 
159
 
 
160
    :param control_dir: Control directory relative to which to lookup the
 
161
        location.
 
162
    :param location: Location to look up
 
163
    :return: branch to open
 
164
    """
 
165
    try:
 
166
        # Perhaps it's a colocated branch?
 
167
        return control_dir.open_branch(location, 
 
168
            possible_transports=possible_transports)
 
169
    except (errors.NotBranchError, errors.NoColocatedBranchSupport):
 
170
        this_url = _get_branch_location(control_dir)
 
171
        return Branch.open(
 
172
            urlutils.join(
 
173
                this_url, '..', urlutils.escape(location)))
 
174
 
 
175
 
 
176
def open_nearby_branch(near=None, location=None, possible_transports=None):
 
177
    """Open a nearby branch.
 
178
 
 
179
    :param near: Optional location of container from which to open branch
 
180
    :param location: Location of the branch
 
181
    :return: Branch instance
 
182
    """
 
183
    if near is None:
 
184
        if location is None:
 
185
            location = "."
 
186
        try:
 
187
            return Branch.open(location,
 
188
                possible_transports=possible_transports)
 
189
        except errors.NotBranchError:
 
190
            near = "."
 
191
    cdir = controldir.ControlDir.open(near,
 
192
        possible_transports=possible_transports)
 
193
    return open_sibling_branch(cdir, location,
 
194
        possible_transports=possible_transports)
 
195
 
 
196
 
 
197
def iter_sibling_branches(control_dir, possible_transports=None):
 
198
    """Iterate over the siblings of a branch.
 
199
 
 
200
    :param control_dir: Control directory for which to look up the siblings
 
201
    :return: Iterator over tuples with branch name and branch object
 
202
    """
 
203
    seen_urls = set()
 
204
    try:
 
205
        reference = control_dir.get_branch_reference()
 
206
    except errors.NotBranchError:
 
207
        # There is no active branch, just return the colocated branches.
 
208
        for name, branch in viewitems(control_dir.get_branches()):
 
209
            yield name, branch
 
210
        return
 
211
    if reference is not None:
 
212
        ref_branch = Branch.open(reference,
 
213
            possible_transports=possible_transports)
 
214
    else:
 
215
        ref_branch = None
 
216
    if ref_branch is None or ref_branch.name:
 
217
        if ref_branch is not None:
 
218
            control_dir = ref_branch.controldir
 
219
        for name, branch in viewitems(control_dir.get_branches()):
 
220
            yield name, branch
 
221
    else:
 
222
        repo = ref_branch.controldir.find_repository()
 
223
        for branch in repo.find_branches(using=True):
 
224
            name = urlutils.relative_url(repo.user_url,
 
225
                branch.user_url).rstrip("/")
 
226
            yield name, branch
 
227
 
 
228
 
 
229
def tree_files_for_add(file_list):
 
230
    """
 
231
    Return a tree and list of absolute paths from a file list.
 
232
 
 
233
    Similar to tree_files, but add handles files a bit differently, so it a
 
234
    custom implementation.  In particular, MutableTreeTree.smart_add expects
 
235
    absolute paths, which it immediately converts to relative paths.
 
236
    """
 
237
    # FIXME Would be nice to just return the relative paths like
 
238
    # internal_tree_files does, but there are a large number of unit tests
 
239
    # that assume the current interface to mutabletree.smart_add
 
240
    if file_list:
 
241
        tree, relpath = WorkingTree.open_containing(file_list[0])
 
242
        if tree.supports_views():
 
243
            view_files = tree.views.lookup_view()
 
244
            if view_files:
 
245
                for filename in file_list:
 
246
                    if not osutils.is_inside_any(view_files, filename):
 
247
                        raise errors.FileOutsideView(filename, view_files)
 
248
        file_list = file_list[:]
 
249
        file_list[0] = tree.abspath(relpath)
 
250
    else:
 
251
        tree = WorkingTree.open_containing(u'.')[0]
 
252
        if tree.supports_views():
 
253
            view_files = tree.views.lookup_view()
 
254
            if view_files:
 
255
                file_list = view_files
 
256
                view_str = views.view_display_str(view_files)
 
257
                note(gettext("Ignoring files outside view. View is %s") % view_str)
 
258
    return tree, file_list
 
259
 
 
260
 
 
261
def _get_one_revision(command_name, revisions):
 
262
    if revisions is None:
 
263
        return None
 
264
    if len(revisions) != 1:
 
265
        raise errors.BzrCommandError(gettext(
 
266
            'brz %s --revision takes exactly one revision identifier') % (
 
267
                command_name,))
 
268
    return revisions[0]
 
269
 
 
270
 
 
271
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
 
272
    """Get a revision tree. Not suitable for commands that change the tree.
 
273
    
 
274
    Specifically, the basis tree in dirstate trees is coupled to the dirstate
 
275
    and doing a commit/uncommit/pull will at best fail due to changing the
 
276
    basis revision data.
 
277
 
 
278
    If tree is passed in, it should be already locked, for lifetime management
 
279
    of the trees internal cached state.
 
280
    """
 
281
    if branch is None:
 
282
        branch = tree.branch
 
283
    if revisions is None:
 
284
        if tree is not None:
 
285
            rev_tree = tree.basis_tree()
 
286
        else:
 
287
            rev_tree = branch.basis_tree()
 
288
    else:
 
289
        revision = _get_one_revision(command_name, revisions)
 
290
        rev_tree = revision.as_tree(branch)
 
291
    return rev_tree
 
292
 
 
293
 
 
294
def _get_view_info_for_change_reporter(tree):
 
295
    """Get the view information from a tree for change reporting."""
 
296
    view_info = None
 
297
    try:
 
298
        current_view = tree.views.get_view_info()[0]
 
299
        if current_view is not None:
 
300
            view_info = (current_view, tree.views.lookup_view())
 
301
    except errors.ViewsNotSupported:
 
302
        pass
 
303
    return view_info
 
304
 
 
305
 
 
306
def _open_directory_or_containing_tree_or_branch(filename, directory):
 
307
    """Open the tree or branch containing the specified file, unless
 
308
    the --directory option is used to specify a different branch."""
 
309
    if directory is not None:
 
310
        return (None, Branch.open(directory), filename)
 
311
    return controldir.ControlDir.open_containing_tree_or_branch(filename)
 
312
 
 
313
 
 
314
# TODO: Make sure no commands unconditionally use the working directory as a
 
315
# branch.  If a filename argument is used, the first of them should be used to
 
316
# specify the branch.  (Perhaps this can be factored out into some kind of
 
317
# Argument class, representing a file in a branch, where the first occurrence
 
318
# opens the branch?)
 
319
 
 
320
class cmd_status(Command):
 
321
    __doc__ = """Display status summary.
 
322
 
 
323
    This reports on versioned and unknown files, reporting them
 
324
    grouped by state.  Possible states are:
 
325
 
 
326
    added
 
327
        Versioned in the working copy but not in the previous revision.
 
328
 
 
329
    removed
 
330
        Versioned in the previous revision but removed or deleted
 
331
        in the working copy.
 
332
 
 
333
    renamed
 
334
        Path of this file changed from the previous revision;
 
335
        the text may also have changed.  This includes files whose
 
336
        parent directory was renamed.
 
337
 
 
338
    modified
 
339
        Text has changed since the previous revision.
 
340
 
 
341
    kind changed
 
342
        File kind has been changed (e.g. from file to directory).
 
343
 
 
344
    unknown
 
345
        Not versioned and not matching an ignore pattern.
 
346
 
 
347
    Additionally for directories, symlinks and files with a changed
 
348
    executable bit, Bazaar indicates their type using a trailing
 
349
    character: '/', '@' or '*' respectively. These decorations can be
 
350
    disabled using the '--no-classify' option.
 
351
 
 
352
    To see ignored files use 'brz ignored'.  For details on the
 
353
    changes to file texts, use 'brz diff'.
 
354
 
 
355
    Note that --short or -S gives status flags for each item, similar
 
356
    to Subversion's status command. To get output similar to svn -q,
 
357
    use brz status -SV.
 
358
 
 
359
    If no arguments are specified, the status of the entire working
 
360
    directory is shown.  Otherwise, only the status of the specified
 
361
    files or directories is reported.  If a directory is given, status
 
362
    is reported for everything inside that directory.
 
363
 
 
364
    Before merges are committed, the pending merge tip revisions are
 
365
    shown. To see all pending merge revisions, use the -v option.
 
366
    To skip the display of pending merge information altogether, use
 
367
    the no-pending option or specify a file/directory.
 
368
 
 
369
    To compare the working directory to a specific revision, pass a
 
370
    single revision to the revision argument.
 
371
 
 
372
    To see which files have changed in a specific revision, or between
 
373
    two revisions, pass a revision range to the revision argument.
 
374
    This will produce the same results as calling 'brz diff --summarize'.
 
375
    """
 
376
 
 
377
    # TODO: --no-recurse/-N, --recurse options
 
378
 
 
379
    takes_args = ['file*']
 
380
    takes_options = ['show-ids', 'revision', 'change', 'verbose',
 
381
                     Option('short', help='Use short status indicators.',
 
382
                            short_name='S'),
 
383
                     Option('versioned', help='Only show versioned files.',
 
384
                            short_name='V'),
 
385
                     Option('no-pending', help='Don\'t show pending merges.',
 
386
                           ),
 
387
                     Option('no-classify',
 
388
                            help='Do not mark object type using indicator.',
 
389
                           ),
 
390
                     ]
 
391
    aliases = ['st', 'stat']
 
392
 
 
393
    encoding_type = 'replace'
 
394
    _see_also = ['diff', 'revert', 'status-flags']
 
395
 
 
396
    @display_command
 
397
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
 
398
            versioned=False, no_pending=False, verbose=False,
 
399
            no_classify=False):
 
400
        from .status import show_tree_status
 
401
 
 
402
        if revision and len(revision) > 2:
 
403
            raise errors.BzrCommandError(gettext('brz status --revision takes exactly'
 
404
                                         ' one or two revision specifiers'))
 
405
 
 
406
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
407
        # Avoid asking for specific files when that is not needed.
 
408
        if relfile_list == ['']:
 
409
            relfile_list = None
 
410
            # Don't disable pending merges for full trees other than '.'.
 
411
            if file_list == ['.']:
 
412
                no_pending = True
 
413
        # A specific path within a tree was given.
 
414
        elif relfile_list is not None:
 
415
            no_pending = True
 
416
        show_tree_status(tree, show_ids=show_ids,
 
417
                         specific_files=relfile_list, revision=revision,
 
418
                         to_file=self.outf, short=short, versioned=versioned,
 
419
                         show_pending=(not no_pending), verbose=verbose,
 
420
                         classify=not no_classify)
 
421
 
 
422
 
 
423
class cmd_cat_revision(Command):
 
424
    __doc__ = """Write out metadata for a revision.
 
425
 
 
426
    The revision to print can either be specified by a specific
 
427
    revision identifier, or you can use --revision.
 
428
    """
 
429
 
 
430
    hidden = True
 
431
    takes_args = ['revision_id?']
 
432
    takes_options = ['directory', 'revision']
 
433
    # cat-revision is more for frontends so should be exact
 
434
    encoding = 'strict'
 
435
 
 
436
    def print_revision(self, revisions, revid):
 
437
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
 
438
        record = next(stream)
 
439
        if record.storage_kind == 'absent':
 
440
            raise errors.NoSuchRevision(revisions, revid)
 
441
        revtext = record.get_bytes_as('fulltext')
 
442
        self.outf.write(revtext.decode('utf-8'))
 
443
 
 
444
    @display_command
 
445
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
446
        if revision_id is not None and revision is not None:
 
447
            raise errors.BzrCommandError(gettext('You can only supply one of'
 
448
                                         ' revision_id or --revision'))
 
449
        if revision_id is None and revision is None:
 
450
            raise errors.BzrCommandError(gettext('You must supply either'
 
451
                                         ' --revision or a revision_id'))
 
452
 
 
453
        b = controldir.ControlDir.open_containing_tree_or_branch(directory)[1]
 
454
 
 
455
        revisions = b.repository.revisions
 
456
        if revisions is None:
 
457
            raise errors.BzrCommandError(gettext('Repository %r does not support '
 
458
                'access to raw revision texts'))
 
459
 
 
460
        b.repository.lock_read()
 
461
        try:
 
462
            # TODO: jam 20060112 should cat-revision always output utf-8?
 
463
            if revision_id is not None:
 
464
                revision_id = cache_utf8.encode(revision_id)
 
465
                try:
 
466
                    self.print_revision(revisions, revision_id)
 
467
                except errors.NoSuchRevision:
 
468
                    msg = gettext("The repository {0} contains no revision {1}.").format(
 
469
                        b.repository.base, revision_id)
 
470
                    raise errors.BzrCommandError(msg)
 
471
            elif revision is not None:
 
472
                for rev in revision:
 
473
                    if rev is None:
 
474
                        raise errors.BzrCommandError(
 
475
                            gettext('You cannot specify a NULL revision.'))
 
476
                    rev_id = rev.as_revision_id(b)
 
477
                    self.print_revision(revisions, rev_id)
 
478
        finally:
 
479
            b.repository.unlock()
 
480
        
 
481
 
 
482
class cmd_dump_btree(Command):
 
483
    __doc__ = """Dump the contents of a btree index file to stdout.
 
484
 
 
485
    PATH is a btree index file, it can be any URL. This includes things like
 
486
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
 
487
 
 
488
    By default, the tuples stored in the index file will be displayed. With
 
489
    --raw, we will uncompress the pages, but otherwise display the raw bytes
 
490
    stored in the index.
 
491
    """
 
492
 
 
493
    # TODO: Do we want to dump the internal nodes as well?
 
494
    # TODO: It would be nice to be able to dump the un-parsed information,
 
495
    #       rather than only going through iter_all_entries. However, this is
 
496
    #       good enough for a start
 
497
    hidden = True
 
498
    encoding_type = 'exact'
 
499
    takes_args = ['path']
 
500
    takes_options = [Option('raw', help='Write the uncompressed bytes out,'
 
501
                                        ' rather than the parsed tuples.'),
 
502
                    ]
 
503
 
 
504
    def run(self, path, raw=False):
 
505
        dirname, basename = osutils.split(path)
 
506
        t = transport.get_transport(dirname)
 
507
        if raw:
 
508
            self._dump_raw_bytes(t, basename)
 
509
        else:
 
510
            self._dump_entries(t, basename)
 
511
 
 
512
    def _get_index_and_bytes(self, trans, basename):
 
513
        """Create a BTreeGraphIndex and raw bytes."""
 
514
        bt = btree_index.BTreeGraphIndex(trans, basename, None)
 
515
        bytes = trans.get_bytes(basename)
 
516
        bt._file = BytesIO(bytes)
 
517
        bt._size = len(bytes)
 
518
        return bt, bytes
 
519
 
 
520
    def _dump_raw_bytes(self, trans, basename):
 
521
        import zlib
 
522
 
 
523
        # We need to parse at least the root node.
 
524
        # This is because the first page of every row starts with an
 
525
        # uncompressed header.
 
526
        bt, bytes = self._get_index_and_bytes(trans, basename)
 
527
        for page_idx, page_start in enumerate(range(0, len(bytes),
 
528
                                                    btree_index._PAGE_SIZE)):
 
529
            page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
 
530
            page_bytes = bytes[page_start:page_end]
 
531
            if page_idx == 0:
 
532
                self.outf.write('Root node:\n')
 
533
                header_end, data = bt._parse_header_from_bytes(page_bytes)
 
534
                self.outf.write(page_bytes[:header_end])
 
535
                page_bytes = data
 
536
            self.outf.write('\nPage %d\n' % (page_idx,))
 
537
            if len(page_bytes) == 0:
 
538
                self.outf.write('(empty)\n');
 
539
            else:
 
540
                decomp_bytes = zlib.decompress(page_bytes)
 
541
                self.outf.write(decomp_bytes)
 
542
                self.outf.write('\n')
 
543
 
 
544
    def _dump_entries(self, trans, basename):
 
545
        try:
 
546
            st = trans.stat(basename)
 
547
        except errors.TransportNotPossible:
 
548
            # We can't stat, so we'll fake it because we have to do the 'get()'
 
549
            # anyway.
 
550
            bt, _ = self._get_index_and_bytes(trans, basename)
 
551
        else:
 
552
            bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
 
553
        for node in bt.iter_all_entries():
 
554
            # Node is made up of:
 
555
            # (index, key, value, [references])
 
556
            try:
 
557
                refs = node[3]
 
558
            except IndexError:
 
559
                refs_as_tuples = None
 
560
            else:
 
561
                refs_as_tuples = static_tuple.as_tuples(refs)
 
562
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
 
563
            self.outf.write('%s\n' % (as_tuple,))
 
564
 
 
565
 
 
566
class cmd_remove_tree(Command):
 
567
    __doc__ = """Remove the working tree from a given branch/checkout.
 
568
 
 
569
    Since a lightweight checkout is little more than a working tree
 
570
    this will refuse to run against one.
 
571
 
 
572
    To re-create the working tree, use "brz checkout".
 
573
    """
 
574
    _see_also = ['checkout', 'working-trees']
 
575
    takes_args = ['location*']
 
576
    takes_options = [
 
577
        Option('force',
 
578
               help='Remove the working tree even if it has '
 
579
                    'uncommitted or shelved changes.'),
 
580
        ]
 
581
 
 
582
    def run(self, location_list, force=False):
 
583
        if not location_list:
 
584
            location_list=['.']
 
585
 
 
586
        for location in location_list:
 
587
            d = controldir.ControlDir.open(location)
 
588
 
 
589
            try:
 
590
                working = d.open_workingtree()
 
591
            except errors.NoWorkingTree:
 
592
                raise errors.BzrCommandError(gettext("No working tree to remove"))
 
593
            except errors.NotLocalUrl:
 
594
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
 
595
                                             " of a remote path"))
 
596
            if not force:
 
597
                if (working.has_changes()):
 
598
                    raise errors.UncommittedChanges(working)
 
599
                if working.get_shelf_manager().last_shelf() is not None:
 
600
                    raise errors.ShelvedChanges(working)
 
601
 
 
602
            if working.user_url != working.branch.user_url:
 
603
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
 
604
                                             " from a lightweight checkout"))
 
605
 
 
606
            d.destroy_workingtree()
 
607
 
 
608
 
 
609
class cmd_repair_workingtree(Command):
 
610
    __doc__ = """Reset the working tree state file.
 
611
 
 
612
    This is not meant to be used normally, but more as a way to recover from
 
613
    filesystem corruption, etc. This rebuilds the working inventory back to a
 
614
    'known good' state. Any new modifications (adding a file, renaming, etc)
 
615
    will be lost, though modified files will still be detected as such.
 
616
 
 
617
    Most users will want something more like "brz revert" or "brz update"
 
618
    unless the state file has become corrupted.
 
619
 
 
620
    By default this attempts to recover the current state by looking at the
 
621
    headers of the state file. If the state file is too corrupted to even do
 
622
    that, you can supply --revision to force the state of the tree.
 
623
    """
 
624
 
 
625
    takes_options = ['revision', 'directory',
 
626
        Option('force',
 
627
               help='Reset the tree even if it doesn\'t appear to be'
 
628
                    ' corrupted.'),
 
629
    ]
 
630
    hidden = True
 
631
 
 
632
    def run(self, revision=None, directory='.', force=False):
 
633
        tree, _ = WorkingTree.open_containing(directory)
 
634
        self.add_cleanup(tree.lock_tree_write().unlock)
 
635
        if not force:
 
636
            try:
 
637
                tree.check_state()
 
638
            except errors.BzrError:
 
639
                pass # There seems to be a real error here, so we'll reset
 
640
            else:
 
641
                # Refuse
 
642
                raise errors.BzrCommandError(gettext(
 
643
                    'The tree does not appear to be corrupt. You probably'
 
644
                    ' want "brz revert" instead. Use "--force" if you are'
 
645
                    ' sure you want to reset the working tree.'))
 
646
        if revision is None:
 
647
            revision_ids = None
 
648
        else:
 
649
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
 
650
        try:
 
651
            tree.reset_state(revision_ids)
 
652
        except errors.BzrError as e:
 
653
            if revision_ids is None:
 
654
                extra = (gettext(', the header appears corrupt, try passing -r -1'
 
655
                         ' to set the state to the last commit'))
 
656
            else:
 
657
                extra = ''
 
658
            raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
 
659
 
 
660
 
 
661
class cmd_revno(Command):
 
662
    __doc__ = """Show current revision number.
 
663
 
 
664
    This is equal to the number of revisions on this branch.
 
665
    """
 
666
 
 
667
    _see_also = ['info']
 
668
    takes_args = ['location?']
 
669
    takes_options = [
 
670
        Option('tree', help='Show revno of working tree.'),
 
671
        'revision',
 
672
        ]
 
673
 
 
674
    @display_command
 
675
    def run(self, tree=False, location=u'.', revision=None):
 
676
        if revision is not None and tree:
 
677
            raise errors.BzrCommandError(gettext("--tree and --revision can "
 
678
                "not be used together"))
 
679
 
 
680
        if tree:
 
681
            try:
 
682
                wt = WorkingTree.open_containing(location)[0]
 
683
                self.add_cleanup(wt.lock_read().unlock)
 
684
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
685
                raise errors.NoWorkingTree(location)
 
686
            b = wt.branch
 
687
            revid = wt.last_revision()
 
688
        else:
 
689
            b = Branch.open_containing(location)[0]
 
690
            self.add_cleanup(b.lock_read().unlock)
 
691
            if revision:
 
692
                if len(revision) != 1:
 
693
                    raise errors.BzrCommandError(gettext(
 
694
                        "Revision numbers only make sense for single "
 
695
                        "revisions, not ranges"))
 
696
                revid = revision[0].as_revision_id(b)
 
697
            else:
 
698
                revid = b.last_revision()
 
699
        try:
 
700
            revno_t = b.revision_id_to_dotted_revno(revid)
 
701
        except errors.NoSuchRevision:
 
702
            revno_t = ('???',)
 
703
        revno = ".".join(str(n) for n in revno_t)
 
704
        self.cleanup_now()
 
705
        self.outf.write(revno + '\n')
 
706
 
 
707
 
 
708
class cmd_revision_info(Command):
 
709
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
710
    """
 
711
    hidden = True
 
712
    takes_args = ['revision_info*']
 
713
    takes_options = [
 
714
        'revision',
 
715
        custom_help('directory',
 
716
            help='Branch to examine, '
 
717
                 'rather than the one containing the working directory.'),
 
718
        Option('tree', help='Show revno of working tree.'),
 
719
        ]
 
720
 
 
721
    @display_command
 
722
    def run(self, revision=None, directory=u'.', tree=False,
 
723
            revision_info_list=[]):
 
724
 
 
725
        try:
 
726
            wt = WorkingTree.open_containing(directory)[0]
 
727
            b = wt.branch
 
728
            self.add_cleanup(wt.lock_read().unlock)
 
729
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
730
            wt = None
 
731
            b = Branch.open_containing(directory)[0]
 
732
            self.add_cleanup(b.lock_read().unlock)
 
733
        revision_ids = []
 
734
        if revision is not None:
 
735
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
 
736
        if revision_info_list is not None:
 
737
            for rev_str in revision_info_list:
 
738
                rev_spec = RevisionSpec.from_string(rev_str)
 
739
                revision_ids.append(rev_spec.as_revision_id(b))
 
740
        # No arguments supplied, default to the last revision
 
741
        if len(revision_ids) == 0:
 
742
            if tree:
 
743
                if wt is None:
 
744
                    raise errors.NoWorkingTree(directory)
 
745
                revision_ids.append(wt.last_revision())
 
746
            else:
 
747
                revision_ids.append(b.last_revision())
 
748
 
 
749
        revinfos = []
 
750
        maxlen = 0
 
751
        for revision_id in revision_ids:
 
752
            try:
 
753
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
 
754
                revno = '.'.join(str(i) for i in dotted_revno)
 
755
            except errors.NoSuchRevision:
 
756
                revno = '???'
 
757
            maxlen = max(maxlen, len(revno))
 
758
            revinfos.append([revno, revision_id])
 
759
 
 
760
        self.cleanup_now()
 
761
        for ri in revinfos:
 
762
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
 
763
 
 
764
 
 
765
class cmd_add(Command):
 
766
    __doc__ = """Add specified files or directories.
 
767
 
 
768
    In non-recursive mode, all the named items are added, regardless
 
769
    of whether they were previously ignored.  A warning is given if
 
770
    any of the named files are already versioned.
 
771
 
 
772
    In recursive mode (the default), files are treated the same way
 
773
    but the behaviour for directories is different.  Directories that
 
774
    are already versioned do not give a warning.  All directories,
 
775
    whether already versioned or not, are searched for files or
 
776
    subdirectories that are neither versioned or ignored, and these
 
777
    are added.  This search proceeds recursively into versioned
 
778
    directories.  If no names are given '.' is assumed.
 
779
 
 
780
    A warning will be printed when nested trees are encountered,
 
781
    unless they are explicitly ignored.
 
782
 
 
783
    Therefore simply saying 'brz add' will version all files that
 
784
    are currently unknown.
 
785
 
 
786
    Adding a file whose parent directory is not versioned will
 
787
    implicitly add the parent, and so on up to the root. This means
 
788
    you should never need to explicitly add a directory, they'll just
 
789
    get added when you add a file in the directory.
 
790
 
 
791
    --dry-run will show which files would be added, but not actually
 
792
    add them.
 
793
 
 
794
    --file-ids-from will try to use the file ids from the supplied path.
 
795
    It looks up ids trying to find a matching parent directory with the
 
796
    same filename, and then by pure path. This option is rarely needed
 
797
    but can be useful when adding the same logical file into two
 
798
    branches that will be merged later (without showing the two different
 
799
    adds as a conflict). It is also useful when merging another project
 
800
    into a subdirectory of this one.
 
801
    
 
802
    Any files matching patterns in the ignore list will not be added
 
803
    unless they are explicitly mentioned.
 
804
    
 
805
    In recursive mode, files larger than the configuration option 
 
806
    add.maximum_file_size will be skipped. Named items are never skipped due
 
807
    to file size.
 
808
    """
 
809
    takes_args = ['file*']
 
810
    takes_options = [
 
811
        Option('no-recurse',
 
812
               help="Don't recursively add the contents of directories.",
 
813
               short_name='N'),
 
814
        Option('dry-run',
 
815
               help="Show what would be done, but don't actually do anything."),
 
816
        'verbose',
 
817
        Option('file-ids-from',
 
818
               type=text_type,
 
819
               help='Lookup file ids from this tree.'),
 
820
        ]
 
821
    encoding_type = 'replace'
 
822
    _see_also = ['remove', 'ignore']
 
823
 
 
824
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
 
825
            file_ids_from=None):
 
826
        import breezy.add
 
827
 
 
828
        base_tree = None
 
829
        if file_ids_from is not None:
 
830
            try:
 
831
                base_tree, base_path = WorkingTree.open_containing(
 
832
                                            file_ids_from)
 
833
            except errors.NoWorkingTree:
 
834
                base_branch, base_path = Branch.open_containing(
 
835
                                            file_ids_from)
 
836
                base_tree = base_branch.basis_tree()
 
837
 
 
838
            action = breezy.add.AddFromBaseAction(base_tree, base_path,
 
839
                          to_file=self.outf, should_print=(not is_quiet()))
 
840
        else:
 
841
            action = breezy.add.AddWithSkipLargeAction(to_file=self.outf,
 
842
                should_print=(not is_quiet()))
 
843
 
 
844
        if base_tree:
 
845
            self.add_cleanup(base_tree.lock_read().unlock)
 
846
        tree, file_list = tree_files_for_add(file_list)
 
847
        added, ignored = tree.smart_add(file_list, not
 
848
            no_recurse, action=action, save=not dry_run)
 
849
        self.cleanup_now()
 
850
        if len(ignored) > 0:
 
851
            if verbose:
 
852
                for glob in sorted(ignored):
 
853
                    for path in ignored[glob]:
 
854
                        self.outf.write(
 
855
                         gettext("ignored {0} matching \"{1}\"\n").format(
 
856
                         path, glob))
 
857
 
 
858
 
 
859
class cmd_mkdir(Command):
 
860
    __doc__ = """Create a new versioned directory.
 
861
 
 
862
    This is equivalent to creating the directory and then adding it.
 
863
    """
 
864
 
 
865
    takes_args = ['dir+']
 
866
    takes_options = [
 
867
        Option(
 
868
            'parents',
 
869
            help='No error if existing, make parent directories as needed.',
 
870
            short_name='p'
 
871
            )
 
872
        ]
 
873
    encoding_type = 'replace'
 
874
 
 
875
    @classmethod
 
876
    def add_file_with_parents(cls, wt, relpath):
 
877
        if wt.path2id(relpath) is not None:
 
878
            return
 
879
        cls.add_file_with_parents(wt, osutils.dirname(relpath))
 
880
        wt.add([relpath])
 
881
 
 
882
    @classmethod
 
883
    def add_file_single(cls, wt, relpath):
 
884
        wt.add([relpath])
 
885
 
 
886
    def run(self, dir_list, parents=False):
 
887
        if parents:
 
888
            add_file = self.add_file_with_parents
 
889
        else:
 
890
            add_file = self.add_file_single
 
891
        for dir in dir_list:
 
892
            wt, relpath = WorkingTree.open_containing(dir)
 
893
            if parents:
 
894
                try:
 
895
                    os.makedirs(dir)
 
896
                except OSError as e:
 
897
                    if e.errno != errno.EEXIST:
 
898
                        raise
 
899
            else:
 
900
                os.mkdir(dir)
 
901
            add_file(wt, relpath)
 
902
            if not is_quiet():
 
903
                self.outf.write(gettext('added %s\n') % dir)
 
904
 
 
905
 
 
906
class cmd_relpath(Command):
 
907
    __doc__ = """Show path of a file relative to root"""
 
908
 
 
909
    takes_args = ['filename']
 
910
    hidden = True
 
911
 
 
912
    @display_command
 
913
    def run(self, filename):
 
914
        # TODO: jam 20050106 Can relpath return a munged path if
 
915
        #       sys.stdout encoding cannot represent it?
 
916
        tree, relpath = WorkingTree.open_containing(filename)
 
917
        self.outf.write(relpath)
 
918
        self.outf.write('\n')
 
919
 
 
920
 
 
921
class cmd_inventory(Command):
 
922
    __doc__ = """Show inventory of the current working copy or a revision.
 
923
 
 
924
    It is possible to limit the output to a particular entry
 
925
    type using the --kind option.  For example: --kind file.
 
926
 
 
927
    It is also possible to restrict the list of files to a specific
 
928
    set. For example: brz inventory --show-ids this/file
 
929
    """
 
930
 
 
931
    hidden = True
 
932
    _see_also = ['ls']
 
933
    takes_options = [
 
934
        'revision',
 
935
        'show-ids',
 
936
        Option('kind',
 
937
               help='List entries of a particular kind: file, directory, symlink.',
 
938
               type=text_type),
 
939
        ]
 
940
    takes_args = ['file*']
 
941
 
 
942
    @display_command
 
943
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
 
944
        if kind and kind not in ['file', 'directory', 'symlink']:
 
945
            raise errors.BzrCommandError(gettext('invalid kind %r specified') % (kind,))
 
946
 
 
947
        revision = _get_one_revision('inventory', revision)
 
948
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
 
949
        self.add_cleanup(work_tree.lock_read().unlock)
 
950
        if revision is not None:
 
951
            tree = revision.as_tree(work_tree.branch)
 
952
 
 
953
            extra_trees = [work_tree]
 
954
            self.add_cleanup(tree.lock_read().unlock)
 
955
        else:
 
956
            tree = work_tree
 
957
            extra_trees = []
 
958
 
 
959
        self.add_cleanup(tree.lock_read().unlock)
 
960
        if file_list is not None:
 
961
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
962
                                      require_versioned=True)
 
963
            # find_ids_across_trees may include some paths that don't
 
964
            # exist in 'tree'.
 
965
            entries = tree.iter_entries_by_dir(specific_file_ids=file_ids)
 
966
        else:
 
967
            entries = tree.iter_entries_by_dir()
 
968
 
 
969
        for path, entry in sorted(entries):
 
970
            if kind and kind != entry.kind:
 
971
                continue
 
972
            if path == "":
 
973
                continue
 
974
            if show_ids:
 
975
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
 
976
            else:
 
977
                self.outf.write(path)
 
978
                self.outf.write('\n')
 
979
 
 
980
 
 
981
class cmd_mv(Command):
 
982
    __doc__ = """Move or rename a file.
 
983
 
 
984
    :Usage:
 
985
        brz mv OLDNAME NEWNAME
 
986
 
 
987
        brz mv SOURCE... DESTINATION
 
988
 
 
989
    If the last argument is a versioned directory, all the other names
 
990
    are moved into it.  Otherwise, there must be exactly two arguments
 
991
    and the file is changed to a new name.
 
992
 
 
993
    If OLDNAME does not exist on the filesystem but is versioned and
 
994
    NEWNAME does exist on the filesystem but is not versioned, mv
 
995
    assumes that the file has been manually moved and only updates
 
996
    its internal inventory to reflect that change.
 
997
    The same is valid when moving many SOURCE files to a DESTINATION.
 
998
 
 
999
    Files cannot be moved between branches.
 
1000
    """
 
1001
 
 
1002
    takes_args = ['names*']
 
1003
    takes_options = [Option("after", help="Move only the brz identifier"
 
1004
        " of the file, because the file has already been moved."),
 
1005
        Option('auto', help='Automatically guess renames.'),
 
1006
        Option('dry-run', help='Avoid making changes when guessing renames.'),
 
1007
        ]
 
1008
    aliases = ['move', 'rename']
 
1009
    encoding_type = 'replace'
 
1010
 
 
1011
    def run(self, names_list, after=False, auto=False, dry_run=False):
 
1012
        if auto:
 
1013
            return self.run_auto(names_list, after, dry_run)
 
1014
        elif dry_run:
 
1015
            raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
 
1016
        if names_list is None:
 
1017
            names_list = []
 
1018
        if len(names_list) < 2:
 
1019
            raise errors.BzrCommandError(gettext("missing file argument"))
 
1020
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
 
1021
        for file_name in rel_names[0:-1]:
 
1022
            if file_name == '':
 
1023
                raise errors.BzrCommandError(gettext("can not move root of branch"))
 
1024
        self.add_cleanup(tree.lock_tree_write().unlock)
 
1025
        self._run(tree, names_list, rel_names, after)
 
1026
 
 
1027
    def run_auto(self, names_list, after, dry_run):
 
1028
        if names_list is not None and len(names_list) > 1:
 
1029
            raise errors.BzrCommandError(gettext('Only one path may be specified to'
 
1030
                                         ' --auto.'))
 
1031
        if after:
 
1032
            raise errors.BzrCommandError(gettext('--after cannot be specified with'
 
1033
                                         ' --auto.'))
 
1034
        work_tree, file_list = WorkingTree.open_containing_paths(
 
1035
            names_list, default_directory='.')
 
1036
        self.add_cleanup(work_tree.lock_tree_write().unlock)
 
1037
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
1038
 
 
1039
    def _run(self, tree, names_list, rel_names, after):
 
1040
        into_existing = osutils.isdir(names_list[-1])
 
1041
        if into_existing and len(names_list) == 2:
 
1042
            # special cases:
 
1043
            # a. case-insensitive filesystem and change case of dir
 
1044
            # b. move directory after the fact (if the source used to be
 
1045
            #    a directory, but now doesn't exist in the working tree
 
1046
            #    and the target is an existing directory, just rename it)
 
1047
            if (not tree.case_sensitive
 
1048
                and rel_names[0].lower() == rel_names[1].lower()):
 
1049
                into_existing = False
 
1050
            else:
 
1051
                # 'fix' the case of a potential 'from'
 
1052
                from_id = tree.path2id(
 
1053
                            tree.get_canonical_inventory_path(rel_names[0]))
 
1054
                if (not osutils.lexists(names_list[0]) and
 
1055
                    from_id and tree.stored_kind(from_id) == "directory"):
 
1056
                    into_existing = False
 
1057
        # move/rename
 
1058
        if into_existing:
 
1059
            # move into existing directory
 
1060
            # All entries reference existing inventory items, so fix them up
 
1061
            # for cicp file-systems.
 
1062
            rel_names = tree.get_canonical_inventory_paths(rel_names)
 
1063
            for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
 
1064
                if not is_quiet():
 
1065
                    self.outf.write("%s => %s\n" % (src, dest))
 
1066
        else:
 
1067
            if len(names_list) != 2:
 
1068
                raise errors.BzrCommandError(gettext('to mv multiple files the'
 
1069
                                             ' destination must be a versioned'
 
1070
                                             ' directory'))
 
1071
 
 
1072
            # for cicp file-systems: the src references an existing inventory
 
1073
            # item:
 
1074
            src = tree.get_canonical_inventory_path(rel_names[0])
 
1075
            # Find the canonical version of the destination:  In all cases, the
 
1076
            # parent of the target must be in the inventory, so we fetch the
 
1077
            # canonical version from there (we do not always *use* the
 
1078
            # canonicalized tail portion - we may be attempting to rename the
 
1079
            # case of the tail)
 
1080
            canon_dest = tree.get_canonical_inventory_path(rel_names[1])
 
1081
            dest_parent = osutils.dirname(canon_dest)
 
1082
            spec_tail = osutils.basename(rel_names[1])
 
1083
            # For a CICP file-system, we need to avoid creating 2 inventory
 
1084
            # entries that differ only by case.  So regardless of the case
 
1085
            # we *want* to use (ie, specified by the user or the file-system),
 
1086
            # we must always choose to use the case of any existing inventory
 
1087
            # items.  The only exception to this is when we are attempting a
 
1088
            # case-only rename (ie, canonical versions of src and dest are
 
1089
            # the same)
 
1090
            dest_id = tree.path2id(canon_dest)
 
1091
            if dest_id is None or tree.path2id(src) == dest_id:
 
1092
                # No existing item we care about, so work out what case we
 
1093
                # are actually going to use.
 
1094
                if after:
 
1095
                    # If 'after' is specified, the tail must refer to a file on disk.
 
1096
                    if dest_parent:
 
1097
                        dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
 
1098
                    else:
 
1099
                        # pathjoin with an empty tail adds a slash, which breaks
 
1100
                        # relpath :(
 
1101
                        dest_parent_fq = tree.basedir
 
1102
 
 
1103
                    dest_tail = osutils.canonical_relpath(
 
1104
                                    dest_parent_fq,
 
1105
                                    osutils.pathjoin(dest_parent_fq, spec_tail))
 
1106
                else:
 
1107
                    # not 'after', so case as specified is used
 
1108
                    dest_tail = spec_tail
 
1109
            else:
 
1110
                # Use the existing item so 'mv' fails with AlreadyVersioned.
 
1111
                dest_tail = os.path.basename(canon_dest)
 
1112
            dest = osutils.pathjoin(dest_parent, dest_tail)
 
1113
            mutter("attempting to move %s => %s", src, dest)
 
1114
            tree.rename_one(src, dest, after=after)
 
1115
            if not is_quiet():
 
1116
                self.outf.write("%s => %s\n" % (src, dest))
 
1117
 
 
1118
 
 
1119
class cmd_pull(Command):
 
1120
    __doc__ = """Turn this branch into a mirror of another branch.
 
1121
 
 
1122
    By default, this command only works on branches that have not diverged.
 
1123
    Branches are considered diverged if the destination branch's most recent 
 
1124
    commit is one that has not been merged (directly or indirectly) into the 
 
1125
    parent.
 
1126
 
 
1127
    If branches have diverged, you can use 'brz merge' to integrate the changes
 
1128
    from one into the other.  Once one branch has merged, the other should
 
1129
    be able to pull it again.
 
1130
 
 
1131
    If you want to replace your local changes and just want your branch to
 
1132
    match the remote one, use pull --overwrite. This will work even if the two
 
1133
    branches have diverged.
 
1134
 
 
1135
    If there is no default location set, the first pull will set it (use
 
1136
    --no-remember to avoid setting it). After that, you can omit the
 
1137
    location to use the default.  To change the default, use --remember. The
 
1138
    value will only be saved if the remote location can be accessed.
 
1139
 
 
1140
    The --verbose option will display the revisions pulled using the log_format
 
1141
    configuration option. You can use a different format by overriding it with
 
1142
    -Olog_format=<other_format>.
 
1143
 
 
1144
    Note: The location can be specified either in the form of a branch,
 
1145
    or in the form of a path to a file containing a merge directive generated
 
1146
    with brz send.
 
1147
    """
 
1148
 
 
1149
    _see_also = ['push', 'update', 'status-flags', 'send']
 
1150
    takes_options = ['remember', 'overwrite', 'revision',
 
1151
        custom_help('verbose',
 
1152
            help='Show logs of pulled revisions.'),
 
1153
        custom_help('directory',
 
1154
            help='Branch to pull into, '
 
1155
                 'rather than the one containing the working directory.'),
 
1156
        Option('local',
 
1157
            help="Perform a local pull in a bound "
 
1158
                 "branch.  Local pulls are not applied to "
 
1159
                 "the master branch."
 
1160
            ),
 
1161
        Option('show-base',
 
1162
            help="Show base revision text in conflicts."),
 
1163
        Option('overwrite-tags',
 
1164
            help="Overwrite tags only."),
 
1165
        ]
 
1166
    takes_args = ['location?']
 
1167
    encoding_type = 'replace'
 
1168
 
 
1169
    def run(self, location=None, remember=None, overwrite=False,
 
1170
            revision=None, verbose=False,
 
1171
            directory=None, local=False,
 
1172
            show_base=False, overwrite_tags=False):
 
1173
 
 
1174
        if overwrite:
 
1175
            overwrite = ["history", "tags"]
 
1176
        elif overwrite_tags:
 
1177
            overwrite = ["tags"]
 
1178
        else:
 
1179
            overwrite = []
 
1180
        # FIXME: too much stuff is in the command class
 
1181
        revision_id = None
 
1182
        mergeable = None
 
1183
        if directory is None:
 
1184
            directory = u'.'
 
1185
        try:
 
1186
            tree_to = WorkingTree.open_containing(directory)[0]
 
1187
            branch_to = tree_to.branch
 
1188
            self.add_cleanup(tree_to.lock_write().unlock)
 
1189
        except errors.NoWorkingTree:
 
1190
            tree_to = None
 
1191
            branch_to = Branch.open_containing(directory)[0]
 
1192
            self.add_cleanup(branch_to.lock_write().unlock)
 
1193
            if show_base:
 
1194
                warning(gettext("No working tree, ignoring --show-base"))
 
1195
 
 
1196
        if local and not branch_to.get_bound_location():
 
1197
            raise errors.LocalRequiresBoundBranch()
 
1198
 
 
1199
        possible_transports = []
 
1200
        if location is not None:
 
1201
            try:
 
1202
                mergeable = bundle.read_mergeable_from_url(location,
 
1203
                    possible_transports=possible_transports)
 
1204
            except errors.NotABundle:
 
1205
                mergeable = None
 
1206
 
 
1207
        stored_loc = branch_to.get_parent()
 
1208
        if location is None:
 
1209
            if stored_loc is None:
 
1210
                raise errors.BzrCommandError(gettext("No pull location known or"
 
1211
                                             " specified."))
 
1212
            else:
 
1213
                display_url = urlutils.unescape_for_display(stored_loc,
 
1214
                        self.outf.encoding)
 
1215
                if not is_quiet():
 
1216
                    self.outf.write(gettext("Using saved parent location: %s\n") % display_url)
 
1217
                location = stored_loc
 
1218
 
 
1219
        revision = _get_one_revision('pull', revision)
 
1220
        if mergeable is not None:
 
1221
            if revision is not None:
 
1222
                raise errors.BzrCommandError(gettext(
 
1223
                    'Cannot use -r with merge directives or bundles'))
 
1224
            mergeable.install_revisions(branch_to.repository)
 
1225
            base_revision_id, revision_id, verified = \
 
1226
                mergeable.get_merge_request(branch_to.repository)
 
1227
            branch_from = branch_to
 
1228
        else:
 
1229
            branch_from = Branch.open(location,
 
1230
                possible_transports=possible_transports)
 
1231
            self.add_cleanup(branch_from.lock_read().unlock)
 
1232
            # Remembers if asked explicitly or no previous location is set
 
1233
            if (remember
 
1234
                or (remember is None and branch_to.get_parent() is None)):
 
1235
                # FIXME: This shouldn't be done before the pull
 
1236
                # succeeds... -- vila 2012-01-02
 
1237
                branch_to.set_parent(branch_from.base)
 
1238
 
 
1239
        if revision is not None:
 
1240
            revision_id = revision.as_revision_id(branch_from)
 
1241
 
 
1242
        if tree_to is not None:
 
1243
            view_info = _get_view_info_for_change_reporter(tree_to)
 
1244
            change_reporter = delta._ChangeReporter(
 
1245
                unversioned_filter=tree_to.is_ignored,
 
1246
                view_info=view_info)
 
1247
            result = tree_to.pull(
 
1248
                branch_from, overwrite, revision_id, change_reporter,
 
1249
                local=local, show_base=show_base)
 
1250
        else:
 
1251
            result = branch_to.pull(
 
1252
                branch_from, overwrite, revision_id, local=local)
 
1253
 
 
1254
        result.report(self.outf)
 
1255
        if verbose and result.old_revid != result.new_revid:
 
1256
            log.show_branch_change(
 
1257
                branch_to, self.outf, result.old_revno,
 
1258
                result.old_revid)
 
1259
        if getattr(result, 'tag_conflicts', None):
 
1260
            return 1
 
1261
        else:
 
1262
            return 0
 
1263
 
 
1264
 
 
1265
class cmd_push(Command):
 
1266
    __doc__ = """Update a mirror of this branch.
 
1267
 
 
1268
    The target branch will not have its working tree populated because this
 
1269
    is both expensive, and is not supported on remote file systems.
 
1270
 
 
1271
    Some smart servers or protocols *may* put the working tree in place in
 
1272
    the future.
 
1273
 
 
1274
    This command only works on branches that have not diverged.  Branches are
 
1275
    considered diverged if the destination branch's most recent commit is one
 
1276
    that has not been merged (directly or indirectly) by the source branch.
 
1277
 
 
1278
    If branches have diverged, you can use 'brz push --overwrite' to replace
 
1279
    the other branch completely, discarding its unmerged changes.
 
1280
 
 
1281
    If you want to ensure you have the different changes in the other branch,
 
1282
    do a merge (see brz help merge) from the other branch, and commit that.
 
1283
    After that you will be able to do a push without '--overwrite'.
 
1284
 
 
1285
    If there is no default push location set, the first push will set it (use
 
1286
    --no-remember to avoid setting it).  After that, you can omit the
 
1287
    location to use the default.  To change the default, use --remember. The
 
1288
    value will only be saved if the remote location can be accessed.
 
1289
 
 
1290
    The --verbose option will display the revisions pushed using the log_format
 
1291
    configuration option. You can use a different format by overriding it with
 
1292
    -Olog_format=<other_format>.
 
1293
    """
 
1294
 
 
1295
    _see_also = ['pull', 'update', 'working-trees']
 
1296
    takes_options = ['remember', 'overwrite', 'verbose', 'revision',
 
1297
        Option('create-prefix',
 
1298
               help='Create the path leading up to the branch '
 
1299
                    'if it does not already exist.'),
 
1300
        custom_help('directory',
 
1301
            help='Branch to push from, '
 
1302
                 'rather than the one containing the working directory.'),
 
1303
        Option('use-existing-dir',
 
1304
               help='By default push will fail if the target'
 
1305
                    ' directory exists, but does not already'
 
1306
                    ' have a control directory.  This flag will'
 
1307
                    ' allow push to proceed.'),
 
1308
        Option('stacked',
 
1309
            help='Create a stacked branch that references the public location '
 
1310
                'of the parent branch.'),
 
1311
        Option('stacked-on',
 
1312
            help='Create a stacked branch that refers to another branch '
 
1313
                'for the commit history. Only the work not present in the '
 
1314
                'referenced branch is included in the branch created.',
 
1315
            type=text_type),
 
1316
        Option('strict',
 
1317
               help='Refuse to push if there are uncommitted changes in'
 
1318
               ' the working tree, --no-strict disables the check.'),
 
1319
        Option('no-tree',
 
1320
               help="Don't populate the working tree, even for protocols"
 
1321
               " that support it."),
 
1322
        Option('overwrite-tags',
 
1323
              help="Overwrite tags only."),
 
1324
        ]
 
1325
    takes_args = ['location?']
 
1326
    encoding_type = 'replace'
 
1327
 
 
1328
    def run(self, location=None, remember=None, overwrite=False,
 
1329
        create_prefix=False, verbose=False, revision=None,
 
1330
        use_existing_dir=False, directory=None, stacked_on=None,
 
1331
        stacked=False, strict=None, no_tree=False,
 
1332
        overwrite_tags=False):
 
1333
        from .push import _show_push_branch
 
1334
 
 
1335
        if overwrite:
 
1336
            overwrite = ["history", "tags"]
 
1337
        elif overwrite_tags:
 
1338
            overwrite = ["tags"]
 
1339
        else:
 
1340
            overwrite = []
 
1341
 
 
1342
        if directory is None:
 
1343
            directory = '.'
 
1344
        # Get the source branch
 
1345
        (tree, br_from,
 
1346
         _unused) = controldir.ControlDir.open_containing_tree_or_branch(directory)
 
1347
        # Get the tip's revision_id
 
1348
        revision = _get_one_revision('push', revision)
 
1349
        if revision is not None:
 
1350
            revision_id = revision.in_history(br_from).rev_id
 
1351
        else:
 
1352
            revision_id = None
 
1353
        if tree is not None and revision_id is None:
 
1354
            tree.check_changed_or_out_of_date(
 
1355
                strict, 'push_strict',
 
1356
                more_error='Use --no-strict to force the push.',
 
1357
                more_warning='Uncommitted changes will not be pushed.')
 
1358
        # Get the stacked_on branch, if any
 
1359
        if stacked_on is not None:
 
1360
            stacked_on = urlutils.normalize_url(stacked_on)
 
1361
        elif stacked:
 
1362
            parent_url = br_from.get_parent()
 
1363
            if parent_url:
 
1364
                parent = Branch.open(parent_url)
 
1365
                stacked_on = parent.get_public_branch()
 
1366
                if not stacked_on:
 
1367
                    # I considered excluding non-http url's here, thus forcing
 
1368
                    # 'public' branches only, but that only works for some
 
1369
                    # users, so it's best to just depend on the user spotting an
 
1370
                    # error by the feedback given to them. RBC 20080227.
 
1371
                    stacked_on = parent_url
 
1372
            if not stacked_on:
 
1373
                raise errors.BzrCommandError(gettext(
 
1374
                    "Could not determine branch to refer to."))
 
1375
 
 
1376
        # Get the destination location
 
1377
        if location is None:
 
1378
            stored_loc = br_from.get_push_location()
 
1379
            if stored_loc is None:
 
1380
                parent_loc = br_from.get_parent()
 
1381
                if parent_loc:
 
1382
                    raise errors.BzrCommandError(gettext(
 
1383
                        "No push location known or specified. To push to the "
 
1384
                        "parent branch (at %s), use 'brz push :parent'." %
 
1385
                        urlutils.unescape_for_display(parent_loc,
 
1386
                            self.outf.encoding)))
 
1387
                else:
 
1388
                    raise errors.BzrCommandError(gettext(
 
1389
                        "No push location known or specified."))
 
1390
            else:
 
1391
                display_url = urlutils.unescape_for_display(stored_loc,
 
1392
                        self.outf.encoding)
 
1393
                note(gettext("Using saved push location: %s") % display_url)
 
1394
                location = stored_loc
 
1395
 
 
1396
        _show_push_branch(br_from, revision_id, location, self.outf,
 
1397
            verbose=verbose, overwrite=overwrite, remember=remember,
 
1398
            stacked_on=stacked_on, create_prefix=create_prefix,
 
1399
            use_existing_dir=use_existing_dir, no_tree=no_tree)
 
1400
 
 
1401
 
 
1402
class cmd_branch(Command):
 
1403
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
1404
 
 
1405
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
1406
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
1407
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
 
1408
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
 
1409
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
 
1410
    create ./foo-bar.
 
1411
 
 
1412
    To retrieve the branch as of a particular revision, supply the --revision
 
1413
    parameter, as in "branch foo/bar -r 5".
 
1414
 
 
1415
    The synonyms 'clone' and 'get' for this command are deprecated.
 
1416
    """
 
1417
 
 
1418
    _see_also = ['checkout']
 
1419
    takes_args = ['from_location', 'to_location?']
 
1420
    takes_options = ['revision',
 
1421
        Option('hardlink', help='Hard-link working tree files where possible.'),
 
1422
        Option('files-from', type=str,
 
1423
               help="Get file contents from this tree."),
 
1424
        Option('no-tree',
 
1425
            help="Create a branch without a working-tree."),
 
1426
        Option('switch',
 
1427
            help="Switch the checkout in the current directory "
 
1428
                 "to the new branch."),
 
1429
        Option('stacked',
 
1430
            help='Create a stacked branch referring to the source branch. '
 
1431
                'The new branch will depend on the availability of the source '
 
1432
                'branch for all operations.'),
 
1433
        Option('standalone',
 
1434
               help='Do not use a shared repository, even if available.'),
 
1435
        Option('use-existing-dir',
 
1436
               help='By default branch will fail if the target'
 
1437
                    ' directory exists, but does not already'
 
1438
                    ' have a control directory.  This flag will'
 
1439
                    ' allow branch to proceed.'),
 
1440
        Option('bind',
 
1441
            help="Bind new branch to from location."),
 
1442
        ]
 
1443
 
 
1444
    def run(self, from_location, to_location=None, revision=None,
 
1445
            hardlink=False, stacked=False, standalone=False, no_tree=False,
 
1446
            use_existing_dir=False, switch=False, bind=False,
 
1447
            files_from=None):
 
1448
        from breezy import switch as _mod_switch
 
1449
        accelerator_tree, br_from = controldir.ControlDir.open_tree_or_branch(
 
1450
            from_location)
 
1451
        if not (hardlink or files_from):
 
1452
            # accelerator_tree is usually slower because you have to read N
 
1453
            # files (no readahead, lots of seeks, etc), but allow the user to
 
1454
            # explicitly request it
 
1455
            accelerator_tree = None
 
1456
        if files_from is not None and files_from != from_location:
 
1457
            accelerator_tree = WorkingTree.open(files_from)
 
1458
        revision = _get_one_revision('branch', revision)
 
1459
        self.add_cleanup(br_from.lock_read().unlock)
 
1460
        if revision is not None:
 
1461
            revision_id = revision.as_revision_id(br_from)
 
1462
        else:
 
1463
            # FIXME - wt.last_revision, fallback to branch, fall back to
 
1464
            # None or perhaps NULL_REVISION to mean copy nothing
 
1465
            # RBC 20060209
 
1466
            revision_id = br_from.last_revision()
 
1467
        if to_location is None:
 
1468
            to_location = getattr(br_from, "name", None)
 
1469
            if not to_location:
 
1470
                to_location = urlutils.derive_to_location(from_location)
 
1471
        to_transport = transport.get_transport(to_location)
 
1472
        try:
 
1473
            to_transport.mkdir('.')
 
1474
        except errors.FileExists:
 
1475
            try:
 
1476
                to_dir = controldir.ControlDir.open_from_transport(
 
1477
                    to_transport)
 
1478
            except errors.NotBranchError:
 
1479
                if not use_existing_dir:
 
1480
                    raise errors.BzrCommandError(gettext('Target directory "%s" '
 
1481
                        'already exists.') % to_location)
 
1482
                else:
 
1483
                    to_dir = None
 
1484
            else:
 
1485
                try:
 
1486
                    to_dir.open_branch()
 
1487
                except errors.NotBranchError:
 
1488
                    pass
 
1489
                else:
 
1490
                    raise errors.AlreadyBranchError(to_location)
 
1491
        except errors.NoSuchFile:
 
1492
            raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
 
1493
                                         % to_location)
 
1494
        else:
 
1495
            to_dir = None
 
1496
        if to_dir is None:
 
1497
            try:
 
1498
                # preserve whatever source format we have.
 
1499
                to_dir = br_from.controldir.sprout(
 
1500
                    to_transport.base, revision_id,
 
1501
                    possible_transports=[to_transport],
 
1502
                    accelerator_tree=accelerator_tree, hardlink=hardlink,
 
1503
                    stacked=stacked, force_new_repo=standalone,
 
1504
                    create_tree_if_local=not no_tree, source_branch=br_from)
 
1505
                branch = to_dir.open_branch(
 
1506
                    possible_transports=[
 
1507
                        br_from.controldir.root_transport, to_transport])
 
1508
            except errors.NoSuchRevision:
 
1509
                to_transport.delete_tree('.')
 
1510
                msg = gettext("The branch {0} has no revision {1}.").format(
 
1511
                    from_location, revision)
 
1512
                raise errors.BzrCommandError(msg)
 
1513
        else:
 
1514
            try:
 
1515
                to_repo = to_dir.open_repository()
 
1516
            except errors.NoRepositoryPresent:
 
1517
                to_repo = to_dir.create_repository()
 
1518
            to_repo.fetch(br_from.repository, revision_id=revision_id)
 
1519
            branch = br_from.sprout(to_dir, revision_id=revision_id)
 
1520
        br_from.tags.merge_to(branch.tags)
 
1521
 
 
1522
        # If the source branch is stacked, the new branch may
 
1523
        # be stacked whether we asked for that explicitly or not.
 
1524
        # We therefore need a try/except here and not just 'if stacked:'
 
1525
        try:
 
1526
            note(gettext('Created new stacked branch referring to %s.') %
 
1527
                branch.get_stacked_on_url())
 
1528
        except (errors.NotStacked, errors.UnstackableBranchFormat,
 
1529
            errors.UnstackableRepositoryFormat) as e:
 
1530
            note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
 
1531
        if bind:
 
1532
            # Bind to the parent
 
1533
            parent_branch = Branch.open(from_location)
 
1534
            branch.bind(parent_branch)
 
1535
            note(gettext('New branch bound to %s') % from_location)
 
1536
        if switch:
 
1537
            # Switch to the new branch
 
1538
            wt, _ = WorkingTree.open_containing('.')
 
1539
            _mod_switch.switch(wt.controldir, branch)
 
1540
            note(gettext('Switched to branch: %s'),
 
1541
                urlutils.unescape_for_display(branch.base, 'utf-8'))
 
1542
 
 
1543
 
 
1544
class cmd_branches(Command):
 
1545
    __doc__ = """List the branches available at the current location.
 
1546
 
 
1547
    This command will print the names of all the branches at the current
 
1548
    location.
 
1549
    """
 
1550
 
 
1551
    takes_args = ['location?']
 
1552
    takes_options = [
 
1553
                  Option('recursive', short_name='R',
 
1554
                         help='Recursively scan for branches rather than '
 
1555
                              'just looking in the specified location.')]
 
1556
 
 
1557
    def run(self, location=".", recursive=False):
 
1558
        if recursive:
 
1559
            t = transport.get_transport(location)
 
1560
            if not t.listable():
 
1561
                raise errors.BzrCommandError(
 
1562
                    "Can't scan this type of location.")
 
1563
            for b in controldir.ControlDir.find_branches(t):
 
1564
                self.outf.write("%s\n" % urlutils.unescape_for_display(
 
1565
                    urlutils.relative_url(t.base, b.base),
 
1566
                    self.outf.encoding).rstrip("/"))
 
1567
        else:
 
1568
            dir = controldir.ControlDir.open_containing(location)[0]
 
1569
            try:
 
1570
                active_branch = dir.open_branch(name="")
 
1571
            except errors.NotBranchError:
 
1572
                active_branch = None
 
1573
            names = {}
 
1574
            for name, branch in iter_sibling_branches(dir):
 
1575
                if name == "":
 
1576
                    continue
 
1577
                active = (active_branch is not None and
 
1578
                          active_branch.base == branch.base)
 
1579
                names[name] = active
 
1580
            # Only mention the current branch explicitly if it's not
 
1581
            # one of the colocated branches
 
1582
            if not any(viewvalues(names)) and active_branch is not None:
 
1583
                self.outf.write("* %s\n" % gettext("(default)"))
 
1584
            for name in sorted(names):
 
1585
                active = names[name]
 
1586
                if active:
 
1587
                    prefix = "*"
 
1588
                else:
 
1589
                    prefix = " "
 
1590
                self.outf.write("%s %s\n" % (
 
1591
                    prefix, name.encode(self.outf.encoding)))
 
1592
 
 
1593
 
 
1594
class cmd_checkout(Command):
 
1595
    __doc__ = """Create a new checkout of an existing branch.
 
1596
 
 
1597
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
 
1598
    the branch found in '.'. This is useful if you have removed the working tree
 
1599
    or if it was never created - i.e. if you pushed the branch to its current
 
1600
    location using SFTP.
 
1601
 
 
1602
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
 
1603
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
 
1604
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
 
1605
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
 
1606
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
 
1607
    create ./foo-bar.
 
1608
 
 
1609
    To retrieve the branch as of a particular revision, supply the --revision
 
1610
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
 
1611
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
 
1612
    code.)
 
1613
    """
 
1614
 
 
1615
    _see_also = ['checkouts', 'branch', 'working-trees', 'remove-tree']
 
1616
    takes_args = ['branch_location?', 'to_location?']
 
1617
    takes_options = ['revision',
 
1618
                     Option('lightweight',
 
1619
                            help="Perform a lightweight checkout.  Lightweight "
 
1620
                                 "checkouts depend on access to the branch for "
 
1621
                                 "every operation.  Normal checkouts can perform "
 
1622
                                 "common operations like diff and status without "
 
1623
                                 "such access, and also support local commits."
 
1624
                            ),
 
1625
                     Option('files-from', type=str,
 
1626
                            help="Get file contents from this tree."),
 
1627
                     Option('hardlink',
 
1628
                            help='Hard-link working tree files where possible.'
 
1629
                            ),
 
1630
                     ]
 
1631
    aliases = ['co']
 
1632
 
 
1633
    def run(self, branch_location=None, to_location=None, revision=None,
 
1634
            lightweight=False, files_from=None, hardlink=False):
 
1635
        if branch_location is None:
 
1636
            branch_location = osutils.getcwd()
 
1637
            to_location = branch_location
 
1638
        accelerator_tree, source = controldir.ControlDir.open_tree_or_branch(
 
1639
            branch_location)
 
1640
        if not (hardlink or files_from):
 
1641
            # accelerator_tree is usually slower because you have to read N
 
1642
            # files (no readahead, lots of seeks, etc), but allow the user to
 
1643
            # explicitly request it
 
1644
            accelerator_tree = None
 
1645
        revision = _get_one_revision('checkout', revision)
 
1646
        if files_from is not None and files_from != branch_location:
 
1647
            accelerator_tree = WorkingTree.open(files_from)
 
1648
        if revision is not None:
 
1649
            revision_id = revision.as_revision_id(source)
 
1650
        else:
 
1651
            revision_id = None
 
1652
        if to_location is None:
 
1653
            to_location = urlutils.derive_to_location(branch_location)
 
1654
        # if the source and to_location are the same,
 
1655
        # and there is no working tree,
 
1656
        # then reconstitute a branch
 
1657
        if (osutils.abspath(to_location) ==
 
1658
            osutils.abspath(branch_location)):
 
1659
            try:
 
1660
                source.controldir.open_workingtree()
 
1661
            except errors.NoWorkingTree:
 
1662
                source.controldir.create_workingtree(revision_id)
 
1663
                return
 
1664
        source.create_checkout(to_location, revision_id, lightweight,
 
1665
                               accelerator_tree, hardlink)
 
1666
 
 
1667
 
 
1668
class cmd_renames(Command):
 
1669
    __doc__ = """Show list of renamed files.
 
1670
    """
 
1671
    # TODO: Option to show renames between two historical versions.
 
1672
 
 
1673
    # TODO: Only show renames under dir, rather than in the whole branch.
 
1674
    _see_also = ['status']
 
1675
    takes_args = ['dir?']
 
1676
 
 
1677
    @display_command
 
1678
    def run(self, dir=u'.'):
 
1679
        tree = WorkingTree.open_containing(dir)[0]
 
1680
        self.add_cleanup(tree.lock_read().unlock)
 
1681
        old_tree = tree.basis_tree()
 
1682
        self.add_cleanup(old_tree.lock_read().unlock)
 
1683
        renames = []
 
1684
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
 
1685
        for f, paths, c, v, p, n, k, e in iterator:
 
1686
            if paths[0] == paths[1]:
 
1687
                continue
 
1688
            if None in (paths):
 
1689
                continue
 
1690
            renames.append(paths)
 
1691
        renames.sort()
 
1692
        for old_name, new_name in renames:
 
1693
            self.outf.write("%s => %s\n" % (old_name, new_name))
 
1694
 
 
1695
 
 
1696
class cmd_update(Command):
 
1697
    __doc__ = """Update a working tree to a new revision.
 
1698
 
 
1699
    This will perform a merge of the destination revision (the tip of the
 
1700
    branch, or the specified revision) into the working tree, and then make
 
1701
    that revision the basis revision for the working tree.  
 
1702
 
 
1703
    You can use this to visit an older revision, or to update a working tree
 
1704
    that is out of date from its branch.
 
1705
    
 
1706
    If there are any uncommitted changes in the tree, they will be carried
 
1707
    across and remain as uncommitted changes after the update.  To discard
 
1708
    these changes, use 'brz revert'.  The uncommitted changes may conflict
 
1709
    with the changes brought in by the change in basis revision.
 
1710
 
 
1711
    If the tree's branch is bound to a master branch, brz will also update
 
1712
    the branch from the master.
 
1713
 
 
1714
    You cannot update just a single file or directory, because each Bazaar
 
1715
    working tree has just a single basis revision.  If you want to restore a
 
1716
    file that has been removed locally, use 'brz revert' instead of 'brz
 
1717
    update'.  If you want to restore a file to its state in a previous
 
1718
    revision, use 'brz revert' with a '-r' option, or use 'brz cat' to write
 
1719
    out the old content of that file to a new location.
 
1720
 
 
1721
    The 'dir' argument, if given, must be the location of the root of a
 
1722
    working tree to update.  By default, the working tree that contains the 
 
1723
    current working directory is used.
 
1724
    """
 
1725
 
 
1726
    _see_also = ['pull', 'working-trees', 'status-flags']
 
1727
    takes_args = ['dir?']
 
1728
    takes_options = ['revision',
 
1729
                     Option('show-base',
 
1730
                            help="Show base revision text in conflicts."),
 
1731
                     ]
 
1732
    aliases = ['up']
 
1733
 
 
1734
    def run(self, dir=None, revision=None, show_base=None):
 
1735
        if revision is not None and len(revision) != 1:
 
1736
            raise errors.brzCommandError(gettext(
 
1737
                "brz update --revision takes exactly one revision"))
 
1738
        if dir is None:
 
1739
            tree = WorkingTree.open_containing('.')[0]
 
1740
        else:
 
1741
            tree, relpath = WorkingTree.open_containing(dir)
 
1742
            if relpath:
 
1743
                # See bug 557886.
 
1744
                raise errors.BzrCommandError(gettext(
 
1745
                    "brz update can only update a whole tree, "
 
1746
                    "not a file or subdirectory"))
 
1747
        branch = tree.branch
 
1748
        possible_transports = []
 
1749
        master = branch.get_master_branch(
 
1750
            possible_transports=possible_transports)
 
1751
        if master is not None:
 
1752
            branch_location = master.base
 
1753
            tree.lock_write()
 
1754
        else:
 
1755
            branch_location = tree.branch.base
 
1756
            tree.lock_tree_write()
 
1757
        self.add_cleanup(tree.unlock)
 
1758
        # get rid of the final '/' and be ready for display
 
1759
        branch_location = urlutils.unescape_for_display(
 
1760
            branch_location.rstrip('/'),
 
1761
            self.outf.encoding)
 
1762
        existing_pending_merges = tree.get_parent_ids()[1:]
 
1763
        if master is None:
 
1764
            old_tip = None
 
1765
        else:
 
1766
            # may need to fetch data into a heavyweight checkout
 
1767
            # XXX: this may take some time, maybe we should display a
 
1768
            # message
 
1769
            old_tip = branch.update(possible_transports)
 
1770
        if revision is not None:
 
1771
            revision_id = revision[0].as_revision_id(branch)
 
1772
        else:
 
1773
            revision_id = branch.last_revision()
 
1774
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
 
1775
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
1776
            note(gettext("Tree is up to date at revision {0} of branch {1}"
 
1777
                        ).format('.'.join(map(str, revno)), branch_location))
 
1778
            return 0
 
1779
        view_info = _get_view_info_for_change_reporter(tree)
 
1780
        change_reporter = delta._ChangeReporter(
 
1781
            unversioned_filter=tree.is_ignored,
 
1782
            view_info=view_info)
 
1783
        try:
 
1784
            conflicts = tree.update(
 
1785
                change_reporter,
 
1786
                possible_transports=possible_transports,
 
1787
                revision=revision_id,
 
1788
                old_tip=old_tip,
 
1789
                show_base=show_base)
 
1790
        except errors.NoSuchRevision as e:
 
1791
            raise errors.BzrCommandError(gettext(
 
1792
                                  "branch has no revision %s\n"
 
1793
                                  "brz update --revision only works"
 
1794
                                  " for a revision in the branch history")
 
1795
                                  % (e.revision))
 
1796
        revno = tree.branch.revision_id_to_dotted_revno(
 
1797
            _mod_revision.ensure_null(tree.last_revision()))
 
1798
        note(gettext('Updated to revision {0} of branch {1}').format(
 
1799
             '.'.join(map(str, revno)), branch_location))
 
1800
        parent_ids = tree.get_parent_ids()
 
1801
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
 
1802
            note(gettext('Your local commits will now show as pending merges with '
 
1803
                 "'brz status', and can be committed with 'brz commit'."))
 
1804
        if conflicts != 0:
 
1805
            return 1
 
1806
        else:
 
1807
            return 0
 
1808
 
 
1809
 
 
1810
class cmd_info(Command):
 
1811
    __doc__ = """Show information about a working tree, branch or repository.
 
1812
 
 
1813
    This command will show all known locations and formats associated to the
 
1814
    tree, branch or repository.
 
1815
 
 
1816
    In verbose mode, statistical information is included with each report.
 
1817
    To see extended statistic information, use a verbosity level of 2 or
 
1818
    higher by specifying the verbose option multiple times, e.g. -vv.
 
1819
 
 
1820
    Branches and working trees will also report any missing revisions.
 
1821
 
 
1822
    :Examples:
 
1823
 
 
1824
      Display information on the format and related locations:
 
1825
 
 
1826
        brz info
 
1827
 
 
1828
      Display the above together with extended format information and
 
1829
      basic statistics (like the number of files in the working tree and
 
1830
      number of revisions in the branch and repository):
 
1831
 
 
1832
        brz info -v
 
1833
 
 
1834
      Display the above together with number of committers to the branch:
 
1835
 
 
1836
        brz info -vv
 
1837
    """
 
1838
    _see_also = ['revno', 'working-trees', 'repositories']
 
1839
    takes_args = ['location?']
 
1840
    takes_options = ['verbose']
 
1841
    encoding_type = 'replace'
 
1842
 
 
1843
    @display_command
 
1844
    def run(self, location=None, verbose=False):
 
1845
        if verbose:
 
1846
            noise_level = get_verbosity_level()
 
1847
        else:
 
1848
            noise_level = 0
 
1849
        from .info import show_bzrdir_info
 
1850
        show_bzrdir_info(controldir.ControlDir.open_containing(location)[0],
 
1851
                         verbose=noise_level, outfile=self.outf)
 
1852
 
 
1853
 
 
1854
class cmd_remove(Command):
 
1855
    __doc__ = """Remove files or directories.
 
1856
 
 
1857
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
 
1858
    delete them if they can easily be recovered using revert otherwise they
 
1859
    will be backed up (adding an extension of the form .~#~). If no options or
 
1860
    parameters are given Bazaar will scan for files that are being tracked by
 
1861
    Bazaar but missing in your tree and stop tracking them for you.
 
1862
    """
 
1863
    takes_args = ['file*']
 
1864
    takes_options = ['verbose',
 
1865
        Option('new', help='Only remove files that have never been committed.'),
 
1866
        RegistryOption.from_kwargs('file-deletion-strategy',
 
1867
            'The file deletion mode to be used.',
 
1868
            title='Deletion Strategy', value_switches=True, enum_switch=False,
 
1869
            safe='Backup changed files (default).',
 
1870
            keep='Delete from brz but leave the working copy.',
 
1871
            no_backup='Don\'t backup changed files.'),
 
1872
        ]
 
1873
    aliases = ['rm', 'del']
 
1874
    encoding_type = 'replace'
 
1875
 
 
1876
    def run(self, file_list, verbose=False, new=False,
 
1877
        file_deletion_strategy='safe'):
 
1878
 
 
1879
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1880
 
 
1881
        if file_list is not None:
 
1882
            file_list = [f for f in file_list]
 
1883
 
 
1884
        self.add_cleanup(tree.lock_write().unlock)
 
1885
        # Heuristics should probably all move into tree.remove_smart or
 
1886
        # some such?
 
1887
        if new:
 
1888
            added = tree.changes_from(tree.basis_tree(),
 
1889
                specific_files=file_list).added
 
1890
            file_list = sorted([f[0] for f in added], reverse=True)
 
1891
            if len(file_list) == 0:
 
1892
                raise errors.BzrCommandError(gettext('No matching files.'))
 
1893
        elif file_list is None:
 
1894
            # missing files show up in iter_changes(basis) as
 
1895
            # versioned-with-no-kind.
 
1896
            missing = []
 
1897
            for change in tree.iter_changes(tree.basis_tree()):
 
1898
                # Find paths in the working tree that have no kind:
 
1899
                if change[1][1] is not None and change[6][1] is None:
 
1900
                    missing.append(change[1][1])
 
1901
            file_list = sorted(missing, reverse=True)
 
1902
            file_deletion_strategy = 'keep'
 
1903
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1904
            keep_files=file_deletion_strategy=='keep',
 
1905
            force=(file_deletion_strategy=='no-backup'))
 
1906
 
 
1907
 
 
1908
class cmd_file_id(Command):
 
1909
    __doc__ = """Print file_id of a particular file or directory.
 
1910
 
 
1911
    The file_id is assigned when the file is first added and remains the
 
1912
    same through all revisions where the file exists, even when it is
 
1913
    moved or renamed.
 
1914
    """
 
1915
 
 
1916
    hidden = True
 
1917
    _see_also = ['inventory', 'ls']
 
1918
    takes_args = ['filename']
 
1919
 
 
1920
    @display_command
 
1921
    def run(self, filename):
 
1922
        tree, relpath = WorkingTree.open_containing(filename)
 
1923
        i = tree.path2id(relpath)
 
1924
        if i is None:
 
1925
            raise errors.NotVersionedError(filename)
 
1926
        else:
 
1927
            self.outf.write(i + '\n')
 
1928
 
 
1929
 
 
1930
class cmd_file_path(Command):
 
1931
    __doc__ = """Print path of file_ids to a file or directory.
 
1932
 
 
1933
    This prints one line for each directory down to the target,
 
1934
    starting at the branch root.
 
1935
    """
 
1936
 
 
1937
    hidden = True
 
1938
    takes_args = ['filename']
 
1939
 
 
1940
    @display_command
 
1941
    def run(self, filename):
 
1942
        tree, relpath = WorkingTree.open_containing(filename)
 
1943
        fid = tree.path2id(relpath)
 
1944
        if fid is None:
 
1945
            raise errors.NotVersionedError(filename)
 
1946
        segments = osutils.splitpath(relpath)
 
1947
        for pos in range(1, len(segments) + 1):
 
1948
            path = osutils.joinpath(segments[:pos])
 
1949
            self.outf.write("%s\n" % tree.path2id(path))
 
1950
 
 
1951
 
 
1952
class cmd_reconcile(Command):
 
1953
    __doc__ = """Reconcile brz metadata in a branch.
 
1954
 
 
1955
    This can correct data mismatches that may have been caused by
 
1956
    previous ghost operations or brz upgrades. You should only
 
1957
    need to run this command if 'brz check' or a brz developer
 
1958
    advises you to run it.
 
1959
 
 
1960
    If a second branch is provided, cross-branch reconciliation is
 
1961
    also attempted, which will check that data like the tree root
 
1962
    id which was not present in very early brz versions is represented
 
1963
    correctly in both branches.
 
1964
 
 
1965
    At the same time it is run it may recompress data resulting in
 
1966
    a potential saving in disk space or performance gain.
 
1967
 
 
1968
    The branch *MUST* be on a listable system such as local disk or sftp.
 
1969
    """
 
1970
 
 
1971
    _see_also = ['check']
 
1972
    takes_args = ['branch?']
 
1973
    takes_options = [
 
1974
        Option('canonicalize-chks',
 
1975
               help='Make sure CHKs are in canonical form (repairs '
 
1976
                    'bug 522637).',
 
1977
               hidden=True),
 
1978
        ]
 
1979
 
 
1980
    def run(self, branch=".", canonicalize_chks=False):
 
1981
        from .reconcile import reconcile
 
1982
        dir = controldir.ControlDir.open(branch)
 
1983
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1984
 
 
1985
 
 
1986
class cmd_revision_history(Command):
 
1987
    __doc__ = """Display the list of revision ids on a branch."""
 
1988
 
 
1989
    _see_also = ['log']
 
1990
    takes_args = ['location?']
 
1991
 
 
1992
    hidden = True
 
1993
 
 
1994
    @display_command
 
1995
    def run(self, location="."):
 
1996
        branch = Branch.open_containing(location)[0]
 
1997
        self.add_cleanup(branch.lock_read().unlock)
 
1998
        graph = branch.repository.get_graph()
 
1999
        history = list(graph.iter_lefthand_ancestry(branch.last_revision(),
 
2000
            [_mod_revision.NULL_REVISION]))
 
2001
        for revid in reversed(history):
 
2002
            self.outf.write(revid)
 
2003
            self.outf.write('\n')
 
2004
 
 
2005
 
 
2006
class cmd_ancestry(Command):
 
2007
    __doc__ = """List all revisions merged into this branch."""
 
2008
 
 
2009
    _see_also = ['log', 'revision-history']
 
2010
    takes_args = ['location?']
 
2011
 
 
2012
    hidden = True
 
2013
 
 
2014
    @display_command
 
2015
    def run(self, location="."):
 
2016
        try:
 
2017
            wt = WorkingTree.open_containing(location)[0]
 
2018
        except errors.NoWorkingTree:
 
2019
            b = Branch.open(location)
 
2020
            last_revision = b.last_revision()
 
2021
        else:
 
2022
            b = wt.branch
 
2023
            last_revision = wt.last_revision()
 
2024
 
 
2025
        self.add_cleanup(b.repository.lock_read().unlock)
 
2026
        graph = b.repository.get_graph()
 
2027
        revisions = [revid for revid, parents in
 
2028
            graph.iter_ancestry([last_revision])]
 
2029
        for revision_id in reversed(revisions):
 
2030
            if _mod_revision.is_null(revision_id):
 
2031
                continue
 
2032
            self.outf.write(revision_id + '\n')
 
2033
 
 
2034
 
 
2035
class cmd_init(Command):
 
2036
    __doc__ = """Make a directory into a versioned branch.
 
2037
 
 
2038
    Use this to create an empty branch, or before importing an
 
2039
    existing project.
 
2040
 
 
2041
    If there is a repository in a parent directory of the location, then
 
2042
    the history of the branch will be stored in the repository.  Otherwise
 
2043
    init creates a standalone branch which carries its own history
 
2044
    in the .bzr directory.
 
2045
 
 
2046
    If there is already a branch at the location but it has no working tree,
 
2047
    the tree can be populated with 'brz checkout'.
 
2048
 
 
2049
    Recipe for importing a tree of files::
 
2050
 
 
2051
        cd ~/project
 
2052
        brz init
 
2053
        brz add .
 
2054
        brz status
 
2055
        brz commit -m "imported project"
 
2056
    """
 
2057
 
 
2058
    _see_also = ['init-repository', 'branch', 'checkout']
 
2059
    takes_args = ['location?']
 
2060
    takes_options = [
 
2061
        Option('create-prefix',
 
2062
               help='Create the path leading up to the branch '
 
2063
                    'if it does not already exist.'),
 
2064
         RegistryOption('format',
 
2065
                help='Specify a format for this branch. '
 
2066
                'See "help formats".',
 
2067
                lazy_registry=('breezy.controldir', 'format_registry'),
 
2068
                converter=lambda name: controldir.format_registry.make_controldir(name),
 
2069
                value_switches=True,
 
2070
                title="Branch format",
 
2071
                ),
 
2072
         Option('append-revisions-only',
 
2073
                help='Never change revnos or the existing log.'
 
2074
                '  Append revisions to it only.'),
 
2075
         Option('no-tree',
 
2076
                'Create a branch without a working tree.')
 
2077
         ]
 
2078
    def run(self, location=None, format=None, append_revisions_only=False,
 
2079
            create_prefix=False, no_tree=False):
 
2080
        if format is None:
 
2081
            format = controldir.format_registry.make_controldir('default')
 
2082
        if location is None:
 
2083
            location = u'.'
 
2084
 
 
2085
        to_transport = transport.get_transport(location)
 
2086
 
 
2087
        # The path has to exist to initialize a
 
2088
        # branch inside of it.
 
2089
        # Just using os.mkdir, since I don't
 
2090
        # believe that we want to create a bunch of
 
2091
        # locations if the user supplies an extended path
 
2092
        try:
 
2093
            to_transport.ensure_base()
 
2094
        except errors.NoSuchFile:
 
2095
            if not create_prefix:
 
2096
                raise errors.BzrCommandError(gettext("Parent directory of %s"
 
2097
                    " does not exist."
 
2098
                    "\nYou may supply --create-prefix to create all"
 
2099
                    " leading parent directories.")
 
2100
                    % location)
 
2101
            to_transport.create_prefix()
 
2102
 
 
2103
        try:
 
2104
            a_controldir = controldir.ControlDir.open_from_transport(to_transport)
 
2105
        except errors.NotBranchError:
 
2106
            # really a NotBzrDir error...
 
2107
            create_branch = controldir.ControlDir.create_branch_convenience
 
2108
            if no_tree:
 
2109
                force_new_tree = False
 
2110
            else:
 
2111
                force_new_tree = None
 
2112
            branch = create_branch(to_transport.base, format=format,
 
2113
                                   possible_transports=[to_transport],
 
2114
                                   force_new_tree=force_new_tree)
 
2115
            a_controldir = branch.controldir
 
2116
        else:
 
2117
            from .transport.local import LocalTransport
 
2118
            if a_controldir.has_branch():
 
2119
                if (isinstance(to_transport, LocalTransport)
 
2120
                    and not a_controldir.has_workingtree()):
 
2121
                        raise errors.BranchExistsWithoutWorkingTree(location)
 
2122
                raise errors.AlreadyBranchError(location)
 
2123
            branch = a_controldir.create_branch()
 
2124
            if not no_tree and not a_controldir.has_workingtree():
 
2125
                a_controldir.create_workingtree()
 
2126
        if append_revisions_only:
 
2127
            try:
 
2128
                branch.set_append_revisions_only(True)
 
2129
            except errors.UpgradeRequired:
 
2130
                raise errors.BzrCommandError(gettext('This branch format cannot be set'
 
2131
                    ' to append-revisions-only.  Try --default.'))
 
2132
        if not is_quiet():
 
2133
            from .info import describe_layout, describe_format
 
2134
            try:
 
2135
                tree = a_controldir.open_workingtree(recommend_upgrade=False)
 
2136
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
2137
                tree = None
 
2138
            repository = branch.repository
 
2139
            layout = describe_layout(repository, branch, tree).lower()
 
2140
            format = describe_format(a_controldir, repository, branch, tree)
 
2141
            self.outf.write(gettext("Created a {0} (format: {1})\n").format(
 
2142
                  layout, format))
 
2143
            if repository.is_shared():
 
2144
                #XXX: maybe this can be refactored into transport.path_or_url()
 
2145
                url = repository.controldir.root_transport.external_url()
 
2146
                try:
 
2147
                    url = urlutils.local_path_from_url(url)
 
2148
                except errors.InvalidURL:
 
2149
                    pass
 
2150
                self.outf.write(gettext("Using shared repository: %s\n") % url)
 
2151
 
 
2152
 
 
2153
class cmd_init_repository(Command):
 
2154
    __doc__ = """Create a shared repository for branches to share storage space.
 
2155
 
 
2156
    New branches created under the repository directory will store their
 
2157
    revisions in the repository, not in the branch directory.  For branches
 
2158
    with shared history, this reduces the amount of storage needed and 
 
2159
    speeds up the creation of new branches.
 
2160
 
 
2161
    If the --no-trees option is given then the branches in the repository
 
2162
    will not have working trees by default.  They will still exist as 
 
2163
    directories on disk, but they will not have separate copies of the 
 
2164
    files at a certain revision.  This can be useful for repositories that
 
2165
    store branches which are interacted with through checkouts or remote
 
2166
    branches, such as on a server.
 
2167
 
 
2168
    :Examples:
 
2169
        Create a shared repository holding just branches::
 
2170
 
 
2171
            brz init-repo --no-trees repo
 
2172
            brz init repo/trunk
 
2173
 
 
2174
        Make a lightweight checkout elsewhere::
 
2175
 
 
2176
            brz checkout --lightweight repo/trunk trunk-checkout
 
2177
            cd trunk-checkout
 
2178
            (add files here)
 
2179
    """
 
2180
 
 
2181
    _see_also = ['init', 'branch', 'checkout', 'repositories']
 
2182
    takes_args = ["location"]
 
2183
    takes_options = [RegistryOption('format',
 
2184
                            help='Specify a format for this repository. See'
 
2185
                                 ' "brz help formats" for details.',
 
2186
                            lazy_registry=('breezy.controldir', 'format_registry'),
 
2187
                            converter=lambda name: controldir.format_registry.make_controldir(name),
 
2188
                            value_switches=True, title='Repository format'),
 
2189
                     Option('no-trees',
 
2190
                             help='Branches in the repository will default to'
 
2191
                                  ' not having a working tree.'),
 
2192
                    ]
 
2193
    aliases = ["init-repo"]
 
2194
 
 
2195
    def run(self, location, format=None, no_trees=False):
 
2196
        if format is None:
 
2197
            format = controldir.format_registry.make_controldir('default')
 
2198
 
 
2199
        if location is None:
 
2200
            location = '.'
 
2201
 
 
2202
        to_transport = transport.get_transport(location)
 
2203
 
 
2204
        (repo, newdir, require_stacking, repository_policy) = (
 
2205
            format.initialize_on_transport_ex(to_transport,
 
2206
            create_prefix=True, make_working_trees=not no_trees,
 
2207
            shared_repo=True, force_new_repo=True,
 
2208
            use_existing_dir=True,
 
2209
            repo_format_name=format.repository_format.get_format_string()))
 
2210
        if not is_quiet():
 
2211
            from .info import show_bzrdir_info
 
2212
            show_bzrdir_info(newdir, verbose=0, outfile=self.outf)
 
2213
 
 
2214
 
 
2215
class cmd_diff(Command):
 
2216
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
2217
 
 
2218
    If no arguments are given, all changes for the current tree are listed.
 
2219
    If files are given, only the changes in those files are listed.
 
2220
    Remote and multiple branches can be compared by using the --old and
 
2221
    --new options. If not provided, the default for both is derived from
 
2222
    the first argument, if any, or the current tree if no arguments are
 
2223
    given.
 
2224
 
 
2225
    "brz diff -p1" is equivalent to "brz diff --prefix old/:new/", and
 
2226
    produces patches suitable for "patch -p1".
 
2227
 
 
2228
    Note that when using the -r argument with a range of revisions, the
 
2229
    differences are computed between the two specified revisions.  That
 
2230
    is, the command does not show the changes introduced by the first 
 
2231
    revision in the range.  This differs from the interpretation of 
 
2232
    revision ranges used by "brz log" which includes the first revision
 
2233
    in the range.
 
2234
 
 
2235
    :Exit values:
 
2236
        1 - changed
 
2237
        2 - unrepresentable changes
 
2238
        3 - error
 
2239
        0 - no change
 
2240
 
 
2241
    :Examples:
 
2242
        Shows the difference in the working tree versus the last commit::
 
2243
 
 
2244
            brz diff
 
2245
 
 
2246
        Difference between the working tree and revision 1::
 
2247
 
 
2248
            brz diff -r1
 
2249
 
 
2250
        Difference between revision 3 and revision 1::
 
2251
 
 
2252
            brz diff -r1..3
 
2253
 
 
2254
        Difference between revision 3 and revision 1 for branch xxx::
 
2255
 
 
2256
            brz diff -r1..3 xxx
 
2257
 
 
2258
        The changes introduced by revision 2 (equivalent to -r1..2)::
 
2259
 
 
2260
            brz diff -c2
 
2261
 
 
2262
        To see the changes introduced by revision X::
 
2263
        
 
2264
            brz diff -cX
 
2265
 
 
2266
        Note that in the case of a merge, the -c option shows the changes
 
2267
        compared to the left hand parent. To see the changes against
 
2268
        another parent, use::
 
2269
 
 
2270
            brz diff -r<chosen_parent>..X
 
2271
 
 
2272
        The changes between the current revision and the previous revision
 
2273
        (equivalent to -c-1 and -r-2..-1)
 
2274
 
 
2275
            brz diff -r-2..
 
2276
 
 
2277
        Show just the differences for file NEWS::
 
2278
 
 
2279
            brz diff NEWS
 
2280
 
 
2281
        Show the differences in working tree xxx for file NEWS::
 
2282
 
 
2283
            brz diff xxx/NEWS
 
2284
 
 
2285
        Show the differences from branch xxx to this working tree:
 
2286
 
 
2287
            brz diff --old xxx
 
2288
 
 
2289
        Show the differences between two branches for file NEWS::
 
2290
 
 
2291
            brz diff --old xxx --new yyy NEWS
 
2292
 
 
2293
        Same as 'brz diff' but prefix paths with old/ and new/::
 
2294
 
 
2295
            brz diff --prefix old/:new/
 
2296
 
 
2297
        Show the differences using a custom diff program with options::
 
2298
 
 
2299
            brz diff --using /usr/bin/diff --diff-options -wu
 
2300
    """
 
2301
    _see_also = ['status']
 
2302
    takes_args = ['file*']
 
2303
    takes_options = [
 
2304
        Option('diff-options', type=str,
 
2305
               help='Pass these options to the external diff program.'),
 
2306
        Option('prefix', type=str,
 
2307
               short_name='p',
 
2308
               help='Set prefixes added to old and new filenames, as '
 
2309
                    'two values separated by a colon. (eg "old/:new/").'),
 
2310
        Option('old',
 
2311
            help='Branch/tree to compare from.',
 
2312
            type=text_type,
 
2313
            ),
 
2314
        Option('new',
 
2315
            help='Branch/tree to compare to.',
 
2316
            type=text_type,
 
2317
            ),
 
2318
        'revision',
 
2319
        'change',
 
2320
        Option('using',
 
2321
            help='Use this command to compare files.',
 
2322
            type=text_type,
 
2323
            ),
 
2324
        RegistryOption('format',
 
2325
            short_name='F',
 
2326
            help='Diff format to use.',
 
2327
            lazy_registry=('breezy.diff', 'format_registry'),
 
2328
            title='Diff format'),
 
2329
        Option('context',
 
2330
            help='How many lines of context to show.',
 
2331
            type=int,
 
2332
            ),
 
2333
        ]
 
2334
    aliases = ['di', 'dif']
 
2335
    encoding_type = 'exact'
 
2336
 
 
2337
    @display_command
 
2338
    def run(self, revision=None, file_list=None, diff_options=None,
 
2339
            prefix=None, old=None, new=None, using=None, format=None,
 
2340
            context=None):
 
2341
        from .diff import (get_trees_and_branches_to_diff_locked,
 
2342
            show_diff_trees)
 
2343
 
 
2344
        if prefix == '0':
 
2345
            # diff -p0 format
 
2346
            old_label = ''
 
2347
            new_label = ''
 
2348
        elif prefix == '1' or prefix is None:
 
2349
            old_label = 'old/'
 
2350
            new_label = 'new/'
 
2351
        elif ':' in prefix:
 
2352
            old_label, new_label = prefix.split(":")
 
2353
        else:
 
2354
            raise errors.BzrCommandError(gettext(
 
2355
                '--prefix expects two values separated by a colon'
 
2356
                ' (eg "old/:new/")'))
 
2357
 
 
2358
        if revision and len(revision) > 2:
 
2359
            raise errors.BzrCommandError(gettext('brz diff --revision takes exactly'
 
2360
                                         ' one or two revision specifiers'))
 
2361
 
 
2362
        if using is not None and format is not None:
 
2363
            raise errors.BzrCommandError(gettext(
 
2364
                '{0} and {1} are mutually exclusive').format(
 
2365
                '--using', '--format'))
 
2366
 
 
2367
        (old_tree, new_tree,
 
2368
         old_branch, new_branch,
 
2369
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
 
2370
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
 
2371
        # GNU diff on Windows uses ANSI encoding for filenames
 
2372
        path_encoding = osutils.get_diff_header_encoding()
 
2373
        return show_diff_trees(old_tree, new_tree, sys.stdout,
 
2374
                               specific_files=specific_files,
 
2375
                               external_diff_options=diff_options,
 
2376
                               old_label=old_label, new_label=new_label,
 
2377
                               extra_trees=extra_trees,
 
2378
                               path_encoding=path_encoding,
 
2379
                               using=using, context=context,
 
2380
                               format_cls=format)
 
2381
 
 
2382
 
 
2383
class cmd_deleted(Command):
 
2384
    __doc__ = """List files deleted in the working tree.
 
2385
    """
 
2386
    # TODO: Show files deleted since a previous revision, or
 
2387
    # between two revisions.
 
2388
    # TODO: Much more efficient way to do this: read in new
 
2389
    # directories with readdir, rather than stating each one.  Same
 
2390
    # level of effort but possibly much less IO.  (Or possibly not,
 
2391
    # if the directories are very large...)
 
2392
    _see_also = ['status', 'ls']
 
2393
    takes_options = ['directory', 'show-ids']
 
2394
 
 
2395
    @display_command
 
2396
    def run(self, show_ids=False, directory=u'.'):
 
2397
        tree = WorkingTree.open_containing(directory)[0]
 
2398
        self.add_cleanup(tree.lock_read().unlock)
 
2399
        old = tree.basis_tree()
 
2400
        self.add_cleanup(old.lock_read().unlock)
 
2401
        for path, ie in old.iter_entries_by_dir():
 
2402
            if not tree.has_id(ie.file_id):
 
2403
                self.outf.write(path)
 
2404
                if show_ids:
 
2405
                    self.outf.write(' ')
 
2406
                    self.outf.write(ie.file_id)
 
2407
                self.outf.write('\n')
 
2408
 
 
2409
 
 
2410
class cmd_modified(Command):
 
2411
    __doc__ = """List files modified in working tree.
 
2412
    """
 
2413
 
 
2414
    hidden = True
 
2415
    _see_also = ['status', 'ls']
 
2416
    takes_options = ['directory', 'null']
 
2417
 
 
2418
    @display_command
 
2419
    def run(self, null=False, directory=u'.'):
 
2420
        tree = WorkingTree.open_containing(directory)[0]
 
2421
        self.add_cleanup(tree.lock_read().unlock)
 
2422
        td = tree.changes_from(tree.basis_tree())
 
2423
        self.cleanup_now()
 
2424
        for path, id, kind, text_modified, meta_modified in td.modified:
 
2425
            if null:
 
2426
                self.outf.write(path + '\0')
 
2427
            else:
 
2428
                self.outf.write(osutils.quotefn(path) + '\n')
 
2429
 
 
2430
 
 
2431
class cmd_added(Command):
 
2432
    __doc__ = """List files added in working tree.
 
2433
    """
 
2434
 
 
2435
    hidden = True
 
2436
    _see_also = ['status', 'ls']
 
2437
    takes_options = ['directory', 'null']
 
2438
 
 
2439
    @display_command
 
2440
    def run(self, null=False, directory=u'.'):
 
2441
        wt = WorkingTree.open_containing(directory)[0]
 
2442
        self.add_cleanup(wt.lock_read().unlock)
 
2443
        basis = wt.basis_tree()
 
2444
        self.add_cleanup(basis.lock_read().unlock)
 
2445
        root_id = wt.get_root_id()
 
2446
        for file_id in wt.all_file_ids():
 
2447
            if basis.has_id(file_id):
 
2448
                continue
 
2449
            if root_id == file_id:
 
2450
                continue
 
2451
            path = wt.id2path(file_id)
 
2452
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
 
2453
                continue
 
2454
            if null:
 
2455
                self.outf.write(path + '\0')
 
2456
            else:
 
2457
                self.outf.write(osutils.quotefn(path) + '\n')
 
2458
 
 
2459
 
 
2460
class cmd_root(Command):
 
2461
    __doc__ = """Show the tree root directory.
 
2462
 
 
2463
    The root is the nearest enclosing directory with a .bzr control
 
2464
    directory."""
 
2465
 
 
2466
    takes_args = ['filename?']
 
2467
    @display_command
 
2468
    def run(self, filename=None):
 
2469
        """Print the branch root."""
 
2470
        tree = WorkingTree.open_containing(filename)[0]
 
2471
        self.outf.write(tree.basedir + '\n')
 
2472
 
 
2473
 
 
2474
def _parse_limit(limitstring):
 
2475
    try:
 
2476
        return int(limitstring)
 
2477
    except ValueError:
 
2478
        msg = gettext("The limit argument must be an integer.")
 
2479
        raise errors.BzrCommandError(msg)
 
2480
 
 
2481
 
 
2482
def _parse_levels(s):
 
2483
    try:
 
2484
        return int(s)
 
2485
    except ValueError:
 
2486
        msg = gettext("The levels argument must be an integer.")
 
2487
        raise errors.BzrCommandError(msg)
 
2488
 
 
2489
 
 
2490
class cmd_log(Command):
 
2491
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2492
 
 
2493
    log is brz's default tool for exploring the history of a branch.
 
2494
    The branch to use is taken from the first parameter. If no parameters
 
2495
    are given, the branch containing the working directory is logged.
 
2496
    Here are some simple examples::
 
2497
 
 
2498
      brz log                       log the current branch
 
2499
      brz log foo.py                log a file in its branch
 
2500
      brz log http://server/branch  log a branch on a server
 
2501
 
 
2502
    The filtering, ordering and information shown for each revision can
 
2503
    be controlled as explained below. By default, all revisions are
 
2504
    shown sorted (topologically) so that newer revisions appear before
 
2505
    older ones and descendants always appear before ancestors. If displayed,
 
2506
    merged revisions are shown indented under the revision in which they
 
2507
    were merged.
 
2508
 
 
2509
    :Output control:
 
2510
 
 
2511
      The log format controls how information about each revision is
 
2512
      displayed. The standard log formats are called ``long``, ``short``
 
2513
      and ``line``. The default is long. See ``brz help log-formats``
 
2514
      for more details on log formats.
 
2515
 
 
2516
      The following options can be used to control what information is
 
2517
      displayed::
 
2518
 
 
2519
        -l N        display a maximum of N revisions
 
2520
        -n N        display N levels of revisions (0 for all, 1 for collapsed)
 
2521
        -v          display a status summary (delta) for each revision
 
2522
        -p          display a diff (patch) for each revision
 
2523
        --show-ids  display revision-ids (and file-ids), not just revnos
 
2524
 
 
2525
      Note that the default number of levels to display is a function of the
 
2526
      log format. If the -n option is not used, the standard log formats show
 
2527
      just the top level (mainline).
 
2528
 
 
2529
      Status summaries are shown using status flags like A, M, etc. To see
 
2530
      the changes explained using words like ``added`` and ``modified``
 
2531
      instead, use the -vv option.
 
2532
 
 
2533
    :Ordering control:
 
2534
 
 
2535
      To display revisions from oldest to newest, use the --forward option.
 
2536
      In most cases, using this option will have little impact on the total
 
2537
      time taken to produce a log, though --forward does not incrementally
 
2538
      display revisions like --reverse does when it can.
 
2539
 
 
2540
    :Revision filtering:
 
2541
 
 
2542
      The -r option can be used to specify what revision or range of revisions
 
2543
      to filter against. The various forms are shown below::
 
2544
 
 
2545
        -rX      display revision X
 
2546
        -rX..    display revision X and later
 
2547
        -r..Y    display up to and including revision Y
 
2548
        -rX..Y   display from X to Y inclusive
 
2549
 
 
2550
      See ``brz help revisionspec`` for details on how to specify X and Y.
 
2551
      Some common examples are given below::
 
2552
 
 
2553
        -r-1                show just the tip
 
2554
        -r-10..             show the last 10 mainline revisions
 
2555
        -rsubmit:..         show what's new on this branch
 
2556
        -rancestor:path..   show changes since the common ancestor of this
 
2557
                            branch and the one at location path
 
2558
        -rdate:yesterday..  show changes since yesterday
 
2559
 
 
2560
      When logging a range of revisions using -rX..Y, log starts at
 
2561
      revision Y and searches back in history through the primary
 
2562
      ("left-hand") parents until it finds X. When logging just the
 
2563
      top level (using -n1), an error is reported if X is not found
 
2564
      along the way. If multi-level logging is used (-n0), X may be
 
2565
      a nested merge revision and the log will be truncated accordingly.
 
2566
 
 
2567
    :Path filtering:
 
2568
 
 
2569
      If parameters are given and the first one is not a branch, the log
 
2570
      will be filtered to show only those revisions that changed the
 
2571
      nominated files or directories.
 
2572
 
 
2573
      Filenames are interpreted within their historical context. To log a
 
2574
      deleted file, specify a revision range so that the file existed at
 
2575
      the end or start of the range.
 
2576
 
 
2577
      Historical context is also important when interpreting pathnames of
 
2578
      renamed files/directories. Consider the following example:
 
2579
 
 
2580
      * revision 1: add tutorial.txt
 
2581
      * revision 2: modify tutorial.txt
 
2582
      * revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
 
2583
 
 
2584
      In this case:
 
2585
 
 
2586
      * ``brz log guide.txt`` will log the file added in revision 1
 
2587
 
 
2588
      * ``brz log tutorial.txt`` will log the new file added in revision 3
 
2589
 
 
2590
      * ``brz log -r2 -p tutorial.txt`` will show the changes made to
 
2591
        the original file in revision 2.
 
2592
 
 
2593
      * ``brz log -r2 -p guide.txt`` will display an error message as there
 
2594
        was no file called guide.txt in revision 2.
 
2595
 
 
2596
      Renames are always followed by log. By design, there is no need to
 
2597
      explicitly ask for this (and no way to stop logging a file back
 
2598
      until it was last renamed).
 
2599
 
 
2600
    :Other filtering:
 
2601
 
 
2602
      The --match option can be used for finding revisions that match a
 
2603
      regular expression in a commit message, committer, author or bug.
 
2604
      Specifying the option several times will match any of the supplied
 
2605
      expressions. --match-author, --match-bugs, --match-committer and
 
2606
      --match-message can be used to only match a specific field.
 
2607
 
 
2608
    :Tips & tricks:
 
2609
 
 
2610
      GUI tools and IDEs are often better at exploring history than command
 
2611
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
 
2612
      bzr-explorer shell, or the Loggerhead web interface.  See the Bazaar
 
2613
      Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/> and
 
2614
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
 
2615
 
 
2616
      You may find it useful to add the aliases below to ``bazaar.conf``::
 
2617
 
 
2618
        [ALIASES]
 
2619
        tip = log -r-1
 
2620
        top = log -l10 --line
 
2621
        show = log -v -p
 
2622
 
 
2623
      ``brz tip`` will then show the latest revision while ``brz top``
 
2624
      will show the last 10 mainline revisions. To see the details of a
 
2625
      particular revision X,  ``brz show -rX``.
 
2626
 
 
2627
      If you are interested in looking deeper into a particular merge X,
 
2628
      use ``brz log -n0 -rX``.
 
2629
 
 
2630
      ``brz log -v`` on a branch with lots of history is currently
 
2631
      very slow. A fix for this issue is currently under development.
 
2632
      With or without that fix, it is recommended that a revision range
 
2633
      be given when using the -v option.
 
2634
 
 
2635
      brz has a generic full-text matching plugin, brz-search, that can be
 
2636
      used to find revisions matching user names, commit messages, etc.
 
2637
      Among other features, this plugin can find all revisions containing
 
2638
      a list of words but not others.
 
2639
 
 
2640
      When exploring non-mainline history on large projects with deep
 
2641
      history, the performance of log can be greatly improved by installing
 
2642
      the historycache plugin. This plugin buffers historical information
 
2643
      trading disk space for faster speed.
 
2644
    """
 
2645
    takes_args = ['file*']
 
2646
    _see_also = ['log-formats', 'revisionspec']
 
2647
    takes_options = [
 
2648
            Option('forward',
 
2649
                   help='Show from oldest to newest.'),
 
2650
            'timezone',
 
2651
            custom_help('verbose',
 
2652
                   help='Show files changed in each revision.'),
 
2653
            'show-ids',
 
2654
            'revision',
 
2655
            Option('change',
 
2656
                   type=breezy.option._parse_revision_str,
 
2657
                   short_name='c',
 
2658
                   help='Show just the specified revision.'
 
2659
                   ' See also "help revisionspec".'),
 
2660
            'log-format',
 
2661
            RegistryOption('authors',
 
2662
                'What names to list as authors - first, all or committer.',
 
2663
                title='Authors',
 
2664
                lazy_registry=('breezy.log', 'author_list_registry'),
 
2665
            ),
 
2666
            Option('levels',
 
2667
                   short_name='n',
 
2668
                   help='Number of levels to display - 0 for all, 1 for flat.',
 
2669
                   argname='N',
 
2670
                   type=_parse_levels),
 
2671
            Option('message',
 
2672
                   help='Show revisions whose message matches this '
 
2673
                        'regular expression.',
 
2674
                   type=str,
 
2675
                   hidden=True),
 
2676
            Option('limit',
 
2677
                   short_name='l',
 
2678
                   help='Limit the output to the first N revisions.',
 
2679
                   argname='N',
 
2680
                   type=_parse_limit),
 
2681
            Option('show-diff',
 
2682
                   short_name='p',
 
2683
                   help='Show changes made in each revision as a patch.'),
 
2684
            Option('include-merged',
 
2685
                   help='Show merged revisions like --levels 0 does.'),
 
2686
            Option('include-merges', hidden=True,
 
2687
                   help='Historical alias for --include-merged.'),
 
2688
            Option('omit-merges',
 
2689
                   help='Do not report commits with more than one parent.'),
 
2690
            Option('exclude-common-ancestry',
 
2691
                   help='Display only the revisions that are not part'
 
2692
                   ' of both ancestries (require -rX..Y).'
 
2693
                   ),
 
2694
            Option('signatures',
 
2695
                   help='Show digital signature validity.'),
 
2696
            ListOption('match',
 
2697
                short_name='m',
 
2698
                help='Show revisions whose properties match this '
 
2699
                'expression.',
 
2700
                type=str),
 
2701
            ListOption('match-message',
 
2702
                   help='Show revisions whose message matches this '
 
2703
                   'expression.',
 
2704
                type=str),
 
2705
            ListOption('match-committer',
 
2706
                   help='Show revisions whose committer matches this '
 
2707
                   'expression.',
 
2708
                type=str),
 
2709
            ListOption('match-author',
 
2710
                   help='Show revisions whose authors match this '
 
2711
                   'expression.',
 
2712
                type=str),
 
2713
            ListOption('match-bugs',
 
2714
                   help='Show revisions whose bugs match this '
 
2715
                   'expression.',
 
2716
                type=str)
 
2717
            ]
 
2718
    encoding_type = 'replace'
 
2719
 
 
2720
    @display_command
 
2721
    def run(self, file_list=None, timezone='original',
 
2722
            verbose=False,
 
2723
            show_ids=False,
 
2724
            forward=False,
 
2725
            revision=None,
 
2726
            change=None,
 
2727
            log_format=None,
 
2728
            levels=None,
 
2729
            message=None,
 
2730
            limit=None,
 
2731
            show_diff=False,
 
2732
            include_merged=None,
 
2733
            authors=None,
 
2734
            exclude_common_ancestry=False,
 
2735
            signatures=False,
 
2736
            match=None,
 
2737
            match_message=None,
 
2738
            match_committer=None,
 
2739
            match_author=None,
 
2740
            match_bugs=None,
 
2741
            omit_merges=False,
 
2742
            ):
 
2743
        from .log import (
 
2744
            Logger,
 
2745
            make_log_request_dict,
 
2746
            _get_info_for_log_files,
 
2747
            )
 
2748
        direction = (forward and 'forward') or 'reverse'
 
2749
        if include_merged is None:
 
2750
            include_merged = False
 
2751
        if (exclude_common_ancestry
 
2752
            and (revision is None or len(revision) != 2)):
 
2753
            raise errors.BzrCommandError(gettext(
 
2754
                '--exclude-common-ancestry requires -r with two revisions'))
 
2755
        if include_merged:
 
2756
            if levels is None:
 
2757
                levels = 0
 
2758
            else:
 
2759
                raise errors.BzrCommandError(gettext(
 
2760
                    '{0} and {1} are mutually exclusive').format(
 
2761
                    '--levels', '--include-merged'))
 
2762
 
 
2763
        if change is not None:
 
2764
            if len(change) > 1:
 
2765
                raise errors.RangeInChangeOption()
 
2766
            if revision is not None:
 
2767
                raise errors.BzrCommandError(gettext(
 
2768
                    '{0} and {1} are mutually exclusive').format(
 
2769
                    '--revision', '--change'))
 
2770
            else:
 
2771
                revision = change
 
2772
 
 
2773
        file_ids = []
 
2774
        filter_by_dir = False
 
2775
        if file_list:
 
2776
            # find the file ids to log and check for directory filtering
 
2777
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
 
2778
                revision, file_list, self.add_cleanup)
 
2779
            for relpath, file_id, kind in file_info_list:
 
2780
                if file_id is None:
 
2781
                    raise errors.BzrCommandError(gettext(
 
2782
                        "Path unknown at end or start of revision range: %s") %
 
2783
                        relpath)
 
2784
                # If the relpath is the top of the tree, we log everything
 
2785
                if relpath == '':
 
2786
                    file_ids = []
 
2787
                    break
 
2788
                else:
 
2789
                    file_ids.append(file_id)
 
2790
                filter_by_dir = filter_by_dir or (
 
2791
                    kind in ['directory', 'tree-reference'])
 
2792
        else:
 
2793
            # log everything
 
2794
            # FIXME ? log the current subdir only RBC 20060203
 
2795
            if revision is not None \
 
2796
                    and len(revision) > 0 and revision[0].get_branch():
 
2797
                location = revision[0].get_branch()
 
2798
            else:
 
2799
                location = '.'
 
2800
            dir, relpath = controldir.ControlDir.open_containing(location)
 
2801
            b = dir.open_branch()
 
2802
            self.add_cleanup(b.lock_read().unlock)
 
2803
            rev1, rev2 = _get_revision_range(revision, b, self.name())
 
2804
 
 
2805
        if b.get_config_stack().get('validate_signatures_in_log'):
 
2806
            signatures = True
 
2807
 
 
2808
        if signatures:
 
2809
            if not gpg.GPGStrategy.verify_signatures_available():
 
2810
                raise errors.GpgmeNotInstalled(None)
 
2811
 
 
2812
        # Decide on the type of delta & diff filtering to use
 
2813
        # TODO: add an --all-files option to make this configurable & consistent
 
2814
        if not verbose:
 
2815
            delta_type = None
 
2816
        else:
 
2817
            delta_type = 'full'
 
2818
        if not show_diff:
 
2819
            diff_type = None
 
2820
        elif file_ids:
 
2821
            diff_type = 'partial'
 
2822
        else:
 
2823
            diff_type = 'full'
 
2824
 
 
2825
        # Build the log formatter
 
2826
        if log_format is None:
 
2827
            log_format = log.log_formatter_registry.get_default(b)
 
2828
        # Make a non-encoding output to include the diffs - bug 328007
 
2829
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
 
2830
        lf = log_format(show_ids=show_ids, to_file=self.outf,
 
2831
                        to_exact_file=unencoded_output,
 
2832
                        show_timezone=timezone,
 
2833
                        delta_format=get_verbosity_level(),
 
2834
                        levels=levels,
 
2835
                        show_advice=levels is None,
 
2836
                        author_list_handler=authors)
 
2837
 
 
2838
        # Choose the algorithm for doing the logging. It's annoying
 
2839
        # having multiple code paths like this but necessary until
 
2840
        # the underlying repository format is faster at generating
 
2841
        # deltas or can provide everything we need from the indices.
 
2842
        # The default algorithm - match-using-deltas - works for
 
2843
        # multiple files and directories and is faster for small
 
2844
        # amounts of history (200 revisions say). However, it's too
 
2845
        # slow for logging a single file in a repository with deep
 
2846
        # history, i.e. > 10K revisions. In the spirit of "do no
 
2847
        # evil when adding features", we continue to use the
 
2848
        # original algorithm - per-file-graph - for the "single
 
2849
        # file that isn't a directory without showing a delta" case.
 
2850
        partial_history = revision and b.repository._format.supports_chks
 
2851
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2852
            or delta_type or partial_history)
 
2853
 
 
2854
        match_dict = {}
 
2855
        if match:
 
2856
            match_dict[''] = match
 
2857
        if match_message:
 
2858
            match_dict['message'] = match_message
 
2859
        if match_committer:
 
2860
            match_dict['committer'] = match_committer
 
2861
        if match_author:
 
2862
            match_dict['author'] = match_author
 
2863
        if match_bugs:
 
2864
            match_dict['bugs'] = match_bugs
 
2865
 
 
2866
        # Build the LogRequest and execute it
 
2867
        if len(file_ids) == 0:
 
2868
            file_ids = None
 
2869
        rqst = make_log_request_dict(
 
2870
            direction=direction, specific_fileids=file_ids,
 
2871
            start_revision=rev1, end_revision=rev2, limit=limit,
 
2872
            message_search=message, delta_type=delta_type,
 
2873
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
 
2874
            exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
 
2875
            signature=signatures, omit_merges=omit_merges,
 
2876
            )
 
2877
        Logger(b, rqst).show(lf)
 
2878
 
 
2879
 
 
2880
def _get_revision_range(revisionspec_list, branch, command_name):
 
2881
    """Take the input of a revision option and turn it into a revision range.
 
2882
 
 
2883
    It returns RevisionInfo objects which can be used to obtain the rev_id's
 
2884
    of the desired revisions. It does some user input validations.
 
2885
    """
 
2886
    if revisionspec_list is None:
 
2887
        rev1 = None
 
2888
        rev2 = None
 
2889
    elif len(revisionspec_list) == 1:
 
2890
        rev1 = rev2 = revisionspec_list[0].in_history(branch)
 
2891
    elif len(revisionspec_list) == 2:
 
2892
        start_spec = revisionspec_list[0]
 
2893
        end_spec = revisionspec_list[1]
 
2894
        if end_spec.get_branch() != start_spec.get_branch():
 
2895
            # b is taken from revision[0].get_branch(), and
 
2896
            # show_log will use its revision_history. Having
 
2897
            # different branches will lead to weird behaviors.
 
2898
            raise errors.BzrCommandError(gettext(
 
2899
                "brz %s doesn't accept two revisions in different"
 
2900
                " branches.") % command_name)
 
2901
        if start_spec.spec is None:
 
2902
            # Avoid loading all the history.
 
2903
            rev1 = RevisionInfo(branch, None, None)
 
2904
        else:
 
2905
            rev1 = start_spec.in_history(branch)
 
2906
        # Avoid loading all of history when we know a missing
 
2907
        # end of range means the last revision ...
 
2908
        if end_spec.spec is None:
 
2909
            last_revno, last_revision_id = branch.last_revision_info()
 
2910
            rev2 = RevisionInfo(branch, last_revno, last_revision_id)
 
2911
        else:
 
2912
            rev2 = end_spec.in_history(branch)
 
2913
    else:
 
2914
        raise errors.BzrCommandError(gettext(
 
2915
            'brz %s --revision takes one or two values.') % command_name)
 
2916
    return rev1, rev2
 
2917
 
 
2918
 
 
2919
def _revision_range_to_revid_range(revision_range):
 
2920
    rev_id1 = None
 
2921
    rev_id2 = None
 
2922
    if revision_range[0] is not None:
 
2923
        rev_id1 = revision_range[0].rev_id
 
2924
    if revision_range[1] is not None:
 
2925
        rev_id2 = revision_range[1].rev_id
 
2926
    return rev_id1, rev_id2
 
2927
 
 
2928
def get_log_format(long=False, short=False, line=False, default='long'):
 
2929
    log_format = default
 
2930
    if long:
 
2931
        log_format = 'long'
 
2932
    if short:
 
2933
        log_format = 'short'
 
2934
    if line:
 
2935
        log_format = 'line'
 
2936
    return log_format
 
2937
 
 
2938
 
 
2939
class cmd_touching_revisions(Command):
 
2940
    __doc__ = """Return revision-ids which affected a particular file.
 
2941
 
 
2942
    A more user-friendly interface is "brz log FILE".
 
2943
    """
 
2944
 
 
2945
    hidden = True
 
2946
    takes_args = ["filename"]
 
2947
 
 
2948
    @display_command
 
2949
    def run(self, filename):
 
2950
        tree, relpath = WorkingTree.open_containing(filename)
 
2951
        file_id = tree.path2id(relpath)
 
2952
        b = tree.branch
 
2953
        self.add_cleanup(b.lock_read().unlock)
 
2954
        touching_revs = log.find_touching_revisions(b, file_id)
 
2955
        for revno, revision_id, what in touching_revs:
 
2956
            self.outf.write("%6d %s\n" % (revno, what))
 
2957
 
 
2958
 
 
2959
class cmd_ls(Command):
 
2960
    __doc__ = """List files in a tree.
 
2961
    """
 
2962
 
 
2963
    _see_also = ['status', 'cat']
 
2964
    takes_args = ['path?']
 
2965
    takes_options = [
 
2966
            'verbose',
 
2967
            'revision',
 
2968
            Option('recursive', short_name='R',
 
2969
                   help='Recurse into subdirectories.'),
 
2970
            Option('from-root',
 
2971
                   help='Print paths relative to the root of the branch.'),
 
2972
            Option('unknown', short_name='u',
 
2973
                help='Print unknown files.'),
 
2974
            Option('versioned', help='Print versioned files.',
 
2975
                   short_name='V'),
 
2976
            Option('ignored', short_name='i',
 
2977
                help='Print ignored files.'),
 
2978
            Option('kind', short_name='k',
 
2979
                   help='List entries of a particular kind: file, directory, symlink.',
 
2980
                   type=text_type),
 
2981
            'null',
 
2982
            'show-ids',
 
2983
            'directory',
 
2984
            ]
 
2985
    @display_command
 
2986
    def run(self, revision=None, verbose=False,
 
2987
            recursive=False, from_root=False,
 
2988
            unknown=False, versioned=False, ignored=False,
 
2989
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2990
 
 
2991
        if kind and kind not in ('file', 'directory', 'symlink'):
 
2992
            raise errors.BzrCommandError(gettext('invalid kind specified'))
 
2993
 
 
2994
        if verbose and null:
 
2995
            raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
 
2996
        all = not (unknown or versioned or ignored)
 
2997
 
 
2998
        selection = {'I':ignored, '?':unknown, 'V':versioned}
 
2999
 
 
3000
        if path is None:
 
3001
            fs_path = '.'
 
3002
        else:
 
3003
            if from_root:
 
3004
                raise errors.BzrCommandError(gettext('cannot specify both --from-root'
 
3005
                                             ' and PATH'))
 
3006
            fs_path = path
 
3007
        tree, branch, relpath = \
 
3008
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
3009
 
 
3010
        # Calculate the prefix to use
 
3011
        prefix = None
 
3012
        if from_root:
 
3013
            if relpath:
 
3014
                prefix = relpath + '/'
 
3015
        elif fs_path != '.' and not fs_path.endswith('/'):
 
3016
            prefix = fs_path + '/'
 
3017
 
 
3018
        if revision is not None or tree is None:
 
3019
            tree = _get_one_revision_tree('ls', revision, branch=branch)
 
3020
 
 
3021
        apply_view = False
 
3022
        if isinstance(tree, WorkingTree) and tree.supports_views():
 
3023
            view_files = tree.views.lookup_view()
 
3024
            if view_files:
 
3025
                apply_view = True
 
3026
                view_str = views.view_display_str(view_files)
 
3027
                note(gettext("Ignoring files outside view. View is %s") % view_str)
 
3028
 
 
3029
        self.add_cleanup(tree.lock_read().unlock)
 
3030
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
3031
            from_dir=relpath, recursive=recursive):
 
3032
            # Apply additional masking
 
3033
            if not all and not selection[fc]:
 
3034
                continue
 
3035
            if kind is not None and fkind != kind:
 
3036
                continue
 
3037
            if apply_view:
 
3038
                try:
 
3039
                    if relpath:
 
3040
                        fullpath = osutils.pathjoin(relpath, fp)
 
3041
                    else:
 
3042
                        fullpath = fp
 
3043
                    views.check_path_in_view(tree, fullpath)
 
3044
                except errors.FileOutsideView:
 
3045
                    continue
 
3046
 
 
3047
            # Output the entry
 
3048
            if prefix:
 
3049
                fp = osutils.pathjoin(prefix, fp)
 
3050
            kindch = entry.kind_character()
 
3051
            outstring = fp + kindch
 
3052
            ui.ui_factory.clear_term()
 
3053
            if verbose:
 
3054
                outstring = '%-8s %s' % (fc, outstring)
 
3055
                if show_ids and fid is not None:
 
3056
                    outstring = "%-50s %s" % (outstring, fid)
 
3057
                self.outf.write(outstring + '\n')
 
3058
            elif null:
 
3059
                self.outf.write(fp + '\0')
 
3060
                if show_ids:
 
3061
                    if fid is not None:
 
3062
                        self.outf.write(fid)
 
3063
                    self.outf.write('\0')
 
3064
                self.outf.flush()
 
3065
            else:
 
3066
                if show_ids:
 
3067
                    if fid is not None:
 
3068
                        my_id = fid
 
3069
                    else:
 
3070
                        my_id = ''
 
3071
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
 
3072
                else:
 
3073
                    self.outf.write(outstring + '\n')
 
3074
 
 
3075
 
 
3076
class cmd_unknowns(Command):
 
3077
    __doc__ = """List unknown files.
 
3078
    """
 
3079
 
 
3080
    hidden = True
 
3081
    _see_also = ['ls']
 
3082
    takes_options = ['directory']
 
3083
 
 
3084
    @display_command
 
3085
    def run(self, directory=u'.'):
 
3086
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
3087
            self.outf.write(osutils.quotefn(f) + '\n')
 
3088
 
 
3089
 
 
3090
class cmd_ignore(Command):
 
3091
    __doc__ = """Ignore specified files or patterns.
 
3092
 
 
3093
    See ``brz help patterns`` for details on the syntax of patterns.
 
3094
 
 
3095
    If a .bzrignore file does not exist, the ignore command
 
3096
    will create one and add the specified files or patterns to the newly
 
3097
    created file. The ignore command will also automatically add the 
 
3098
    .bzrignore file to be versioned. Creating a .bzrignore file without
 
3099
    the use of the ignore command will require an explicit add command.
 
3100
 
 
3101
    To remove patterns from the ignore list, edit the .bzrignore file.
 
3102
    After adding, editing or deleting that file either indirectly by
 
3103
    using this command or directly by using an editor, be sure to commit
 
3104
    it.
 
3105
    
 
3106
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
 
3107
    the global ignore file can be found in the application data directory as
 
3108
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
 
3109
    Global ignores are not touched by this command. The global ignore file
 
3110
    can be edited directly using an editor.
 
3111
 
 
3112
    Patterns prefixed with '!' are exceptions to ignore patterns and take
 
3113
    precedence over regular ignores.  Such exceptions are used to specify
 
3114
    files that should be versioned which would otherwise be ignored.
 
3115
    
 
3116
    Patterns prefixed with '!!' act as regular ignore patterns, but have
 
3117
    precedence over the '!' exception patterns.
 
3118
 
 
3119
    :Notes: 
 
3120
        
 
3121
    * Ignore patterns containing shell wildcards must be quoted from
 
3122
      the shell on Unix.
 
3123
 
 
3124
    * Ignore patterns starting with "#" act as comments in the ignore file.
 
3125
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
3126
 
 
3127
    :Examples:
 
3128
        Ignore the top level Makefile::
 
3129
 
 
3130
            brz ignore ./Makefile
 
3131
 
 
3132
        Ignore .class files in all directories...::
 
3133
 
 
3134
            brz ignore "*.class"
 
3135
 
 
3136
        ...but do not ignore "special.class"::
 
3137
 
 
3138
            brz ignore "!special.class"
 
3139
 
 
3140
        Ignore files whose name begins with the "#" character::
 
3141
 
 
3142
            brz ignore "RE:^#"
 
3143
 
 
3144
        Ignore .o files under the lib directory::
 
3145
 
 
3146
            brz ignore "lib/**/*.o"
 
3147
 
 
3148
        Ignore .o files under the lib directory::
 
3149
 
 
3150
            brz ignore "RE:lib/.*\.o"
 
3151
 
 
3152
        Ignore everything but the "debian" toplevel directory::
 
3153
 
 
3154
            brz ignore "RE:(?!debian/).*"
 
3155
        
 
3156
        Ignore everything except the "local" toplevel directory,
 
3157
        but always ignore autosave files ending in ~, even under local/::
 
3158
        
 
3159
            brz ignore "*"
 
3160
            brz ignore "!./local"
 
3161
            brz ignore "!!*~"
 
3162
    """
 
3163
 
 
3164
    _see_also = ['status', 'ignored', 'patterns']
 
3165
    takes_args = ['name_pattern*']
 
3166
    takes_options = ['directory',
 
3167
        Option('default-rules',
 
3168
               help='Display the default ignore rules that brz uses.')
 
3169
        ]
 
3170
 
 
3171
    def run(self, name_pattern_list=None, default_rules=None,
 
3172
            directory=u'.'):
 
3173
        from breezy import ignores
 
3174
        if default_rules is not None:
 
3175
            # dump the default rules and exit
 
3176
            for pattern in ignores.USER_DEFAULTS:
 
3177
                self.outf.write("%s\n" % pattern)
 
3178
            return
 
3179
        if not name_pattern_list:
 
3180
            raise errors.BzrCommandError(gettext("ignore requires at least one "
 
3181
                "NAME_PATTERN or --default-rules."))
 
3182
        name_pattern_list = [globbing.normalize_pattern(p)
 
3183
                             for p in name_pattern_list]
 
3184
        bad_patterns = ''
 
3185
        bad_patterns_count = 0
 
3186
        for p in name_pattern_list:
 
3187
            if not globbing.Globster.is_pattern_valid(p):
 
3188
                bad_patterns_count += 1
 
3189
                bad_patterns += ('\n  %s' % p)
 
3190
        if bad_patterns:
 
3191
            msg = (ngettext('Invalid ignore pattern found. %s', 
 
3192
                            'Invalid ignore patterns found. %s',
 
3193
                            bad_patterns_count) % bad_patterns)
 
3194
            ui.ui_factory.show_error(msg)
 
3195
            raise errors.InvalidPattern('')
 
3196
        for name_pattern in name_pattern_list:
 
3197
            if (name_pattern[0] == '/' or
 
3198
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
 
3199
                raise errors.BzrCommandError(gettext(
 
3200
                    "NAME_PATTERN should not be an absolute path"))
 
3201
        tree, relpath = WorkingTree.open_containing(directory)
 
3202
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
 
3203
        ignored = globbing.Globster(name_pattern_list)
 
3204
        matches = []
 
3205
        self.add_cleanup(tree.lock_read().unlock)
 
3206
        for entry in tree.list_files():
 
3207
            id = entry[3]
 
3208
            if id is not None:
 
3209
                filename = entry[0]
 
3210
                if ignored.match(filename):
 
3211
                    matches.append(filename)
 
3212
        if len(matches) > 0:
 
3213
            self.outf.write(gettext("Warning: the following files are version "
 
3214
                  "controlled and match your ignore pattern:\n%s"
 
3215
                  "\nThese files will continue to be version controlled"
 
3216
                  " unless you 'brz remove' them.\n") % ("\n".join(matches),))
 
3217
 
 
3218
 
 
3219
class cmd_ignored(Command):
 
3220
    __doc__ = """List ignored files and the patterns that matched them.
 
3221
 
 
3222
    List all the ignored files and the ignore pattern that caused the file to
 
3223
    be ignored.
 
3224
 
 
3225
    Alternatively, to list just the files::
 
3226
 
 
3227
        brz ls --ignored
 
3228
    """
 
3229
 
 
3230
    encoding_type = 'replace'
 
3231
    _see_also = ['ignore', 'ls']
 
3232
    takes_options = ['directory']
 
3233
 
 
3234
    @display_command
 
3235
    def run(self, directory=u'.'):
 
3236
        tree = WorkingTree.open_containing(directory)[0]
 
3237
        self.add_cleanup(tree.lock_read().unlock)
 
3238
        for path, file_class, kind, file_id, entry in tree.list_files():
 
3239
            if file_class != 'I':
 
3240
                continue
 
3241
            ## XXX: Slightly inefficient since this was already calculated
 
3242
            pat = tree.is_ignored(path)
 
3243
            self.outf.write('%-50s %s\n' % (path, pat))
 
3244
 
 
3245
 
 
3246
class cmd_lookup_revision(Command):
 
3247
    __doc__ = """Lookup the revision-id from a revision-number
 
3248
 
 
3249
    :Examples:
 
3250
        brz lookup-revision 33
 
3251
    """
 
3252
    hidden = True
 
3253
    takes_args = ['revno']
 
3254
    takes_options = ['directory']
 
3255
 
 
3256
    @display_command
 
3257
    def run(self, revno, directory=u'.'):
 
3258
        try:
 
3259
            revno = int(revno)
 
3260
        except ValueError:
 
3261
            raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
 
3262
                                         % revno)
 
3263
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
 
3264
        self.outf.write("%s\n" % revid)
 
3265
 
 
3266
 
 
3267
class cmd_export(Command):
 
3268
    __doc__ = """Export current or past revision to a destination directory or archive.
 
3269
 
 
3270
    If no revision is specified this exports the last committed revision.
 
3271
 
 
3272
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
3273
    given, try to find the format with the extension. If no extension
 
3274
    is found exports to a directory (equivalent to --format=dir).
 
3275
 
 
3276
    If root is supplied, it will be used as the root directory inside
 
3277
    container formats (tar, zip, etc). If it is not supplied it will default
 
3278
    to the exported filename. The root option has no effect for 'dir' format.
 
3279
 
 
3280
    If branch is omitted then the branch containing the current working
 
3281
    directory will be used.
 
3282
 
 
3283
    Note: Export of tree with non-ASCII filenames to zip is not supported.
 
3284
 
 
3285
      =================       =========================
 
3286
      Supported formats       Autodetected by extension
 
3287
      =================       =========================
 
3288
         dir                         (none)
 
3289
         tar                          .tar
 
3290
         tbz2                    .tar.bz2, .tbz2
 
3291
         tgz                      .tar.gz, .tgz
 
3292
         zip                          .zip
 
3293
      =================       =========================
 
3294
    """
 
3295
    encoding = 'exact'
 
3296
    takes_args = ['dest', 'branch_or_subdir?']
 
3297
    takes_options = ['directory',
 
3298
        Option('format',
 
3299
               help="Type of file to export to.",
 
3300
               type=text_type),
 
3301
        'revision',
 
3302
        Option('filters', help='Apply content filters to export the '
 
3303
                'convenient form.'),
 
3304
        Option('root',
 
3305
               type=str,
 
3306
               help="Name of the root directory inside the exported file."),
 
3307
        Option('per-file-timestamps',
 
3308
               help='Set modification time of files to that of the last '
 
3309
                    'revision in which it was changed.'),
 
3310
        Option('uncommitted',
 
3311
               help='Export the working tree contents rather than that of the '
 
3312
                    'last revision.'),
 
3313
        ]
 
3314
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
 
3315
        root=None, filters=False, per_file_timestamps=False, uncommitted=False,
 
3316
        directory=u'.'):
 
3317
        from .export import export
 
3318
 
 
3319
        if branch_or_subdir is None:
 
3320
            branch_or_subdir = directory
 
3321
 
 
3322
        (tree, b, subdir) = controldir.ControlDir.open_containing_tree_or_branch(
 
3323
            branch_or_subdir)
 
3324
        if tree is not None:
 
3325
            self.add_cleanup(tree.lock_read().unlock)
 
3326
 
 
3327
        if uncommitted:
 
3328
            if tree is None:
 
3329
                raise errors.BzrCommandError(
 
3330
                    gettext("--uncommitted requires a working tree"))
 
3331
            export_tree = tree
 
3332
        else:
 
3333
            export_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
 
3334
        try:
 
3335
            export(export_tree, dest, format, root, subdir, filtered=filters,
 
3336
                   per_file_timestamps=per_file_timestamps)
 
3337
        except errors.NoSuchExportFormat as e:
 
3338
            raise errors.BzrCommandError(
 
3339
                gettext('Unsupported export format: %s') % e.format)
 
3340
 
 
3341
 
 
3342
class cmd_cat(Command):
 
3343
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
3344
 
 
3345
    If no revision is nominated, the last revision is used.
 
3346
 
 
3347
    Note: Take care to redirect standard output when using this command on a
 
3348
    binary file.
 
3349
    """
 
3350
 
 
3351
    _see_also = ['ls']
 
3352
    takes_options = ['directory',
 
3353
        Option('name-from-revision', help='The path name in the old tree.'),
 
3354
        Option('filters', help='Apply content filters to display the '
 
3355
                'convenience form.'),
 
3356
        'revision',
 
3357
        ]
 
3358
    takes_args = ['filename']
 
3359
    encoding_type = 'exact'
 
3360
 
 
3361
    @display_command
 
3362
    def run(self, filename, revision=None, name_from_revision=False,
 
3363
            filters=False, directory=None):
 
3364
        if revision is not None and len(revision) != 1:
 
3365
            raise errors.BzrCommandError(gettext("brz cat --revision takes exactly"
 
3366
                                         " one revision specifier"))
 
3367
        tree, branch, relpath = \
 
3368
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
3369
        self.add_cleanup(branch.lock_read().unlock)
 
3370
        return self._run(tree, branch, relpath, filename, revision,
 
3371
                         name_from_revision, filters)
 
3372
 
 
3373
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
 
3374
        filtered):
 
3375
        if tree is None:
 
3376
            tree = b.basis_tree()
 
3377
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
 
3378
        self.add_cleanup(rev_tree.lock_read().unlock)
 
3379
 
 
3380
        old_file_id = rev_tree.path2id(relpath)
 
3381
 
 
3382
        # TODO: Split out this code to something that generically finds the
 
3383
        # best id for a path across one or more trees; it's like
 
3384
        # find_ids_across_trees but restricted to find just one. -- mbp
 
3385
        # 20110705.
 
3386
        if name_from_revision:
 
3387
            # Try in revision if requested
 
3388
            if old_file_id is None:
 
3389
                raise errors.BzrCommandError(gettext(
 
3390
                    "{0!r} is not present in revision {1}").format(
 
3391
                        filename, rev_tree.get_revision_id()))
 
3392
            else:
 
3393
                actual_file_id = old_file_id
 
3394
        else:
 
3395
            cur_file_id = tree.path2id(relpath)
 
3396
            if cur_file_id is not None and rev_tree.has_id(cur_file_id):
 
3397
                actual_file_id = cur_file_id
 
3398
            elif old_file_id is not None:
 
3399
                actual_file_id = old_file_id
 
3400
            else:
 
3401
                raise errors.BzrCommandError(gettext(
 
3402
                    "{0!r} is not present in revision {1}").format(
 
3403
                        filename, rev_tree.get_revision_id()))
 
3404
        if filtered:
 
3405
            from .filter_tree import ContentFilterTree
 
3406
            filter_tree = ContentFilterTree(rev_tree,
 
3407
                rev_tree._content_filter_stack)
 
3408
            content = filter_tree.get_file_text(actual_file_id)
 
3409
        else:
 
3410
            content = rev_tree.get_file_text(actual_file_id)
 
3411
        self.cleanup_now()
 
3412
        self.outf.write(content)
 
3413
 
 
3414
 
 
3415
class cmd_local_time_offset(Command):
 
3416
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
3417
    hidden = True
 
3418
    @display_command
 
3419
    def run(self):
 
3420
        self.outf.write("%s\n" % osutils.local_time_offset())
 
3421
 
 
3422
 
 
3423
 
 
3424
class cmd_commit(Command):
 
3425
    __doc__ = """Commit changes into a new revision.
 
3426
 
 
3427
    An explanatory message needs to be given for each commit. This is
 
3428
    often done by using the --message option (getting the message from the
 
3429
    command line) or by using the --file option (getting the message from
 
3430
    a file). If neither of these options is given, an editor is opened for
 
3431
    the user to enter the message. To see the changed files in the
 
3432
    boilerplate text loaded into the editor, use the --show-diff option.
 
3433
 
 
3434
    By default, the entire tree is committed and the person doing the
 
3435
    commit is assumed to be the author. These defaults can be overridden
 
3436
    as explained below.
 
3437
 
 
3438
    :Selective commits:
 
3439
 
 
3440
      If selected files are specified, only changes to those files are
 
3441
      committed.  If a directory is specified then the directory and
 
3442
      everything within it is committed.
 
3443
  
 
3444
      When excludes are given, they take precedence over selected files.
 
3445
      For example, to commit only changes within foo, but not changes
 
3446
      within foo/bar::
 
3447
  
 
3448
        brz commit foo -x foo/bar
 
3449
  
 
3450
      A selective commit after a merge is not yet supported.
 
3451
 
 
3452
    :Custom authors:
 
3453
 
 
3454
      If the author of the change is not the same person as the committer,
 
3455
      you can specify the author's name using the --author option. The
 
3456
      name should be in the same format as a committer-id, e.g.
 
3457
      "John Doe <jdoe@example.com>". If there is more than one author of
 
3458
      the change you can specify the option multiple times, once for each
 
3459
      author.
 
3460
  
 
3461
    :Checks:
 
3462
 
 
3463
      A common mistake is to forget to add a new file or directory before
 
3464
      running the commit command. The --strict option checks for unknown
 
3465
      files and aborts the commit if any are found. More advanced pre-commit
 
3466
      checks can be implemented by defining hooks. See ``brz help hooks``
 
3467
      for details.
 
3468
 
 
3469
    :Things to note:
 
3470
 
 
3471
      If you accidentially commit the wrong changes or make a spelling
 
3472
      mistake in the commit message say, you can use the uncommit command
 
3473
      to undo it. See ``brz help uncommit`` for details.
 
3474
 
 
3475
      Hooks can also be configured to run after a commit. This allows you
 
3476
      to trigger updates to external systems like bug trackers. The --fixes
 
3477
      option can be used to record the association between a revision and
 
3478
      one or more bugs. See ``brz help bugs`` for details.
 
3479
    """
 
3480
 
 
3481
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
 
3482
    takes_args = ['selected*']
 
3483
    takes_options = [
 
3484
            ListOption('exclude', type=str, short_name='x',
 
3485
                help="Do not consider changes made to a given path."),
 
3486
            Option('message', type=text_type,
 
3487
                   short_name='m',
 
3488
                   help="Description of the new revision."),
 
3489
            'verbose',
 
3490
             Option('unchanged',
 
3491
                    help='Commit even if nothing has changed.'),
 
3492
             Option('file', type=str,
 
3493
                    short_name='F',
 
3494
                    argname='msgfile',
 
3495
                    help='Take commit message from this file.'),
 
3496
             Option('strict',
 
3497
                    help="Refuse to commit if there are unknown "
 
3498
                    "files in the working tree."),
 
3499
             Option('commit-time', type=str,
 
3500
                    help="Manually set a commit time using commit date "
 
3501
                    "format, e.g. '2009-10-10 08:00:00 +0100'."),
 
3502
             ListOption('fixes', type=str,
 
3503
                    help="Mark a bug as being fixed by this revision "
 
3504
                         "(see \"brz help bugs\")."),
 
3505
             ListOption('author', type=text_type,
 
3506
                    help="Set the author's name, if it's different "
 
3507
                         "from the committer."),
 
3508
             Option('local',
 
3509
                    help="Perform a local commit in a bound "
 
3510
                         "branch.  Local commits are not pushed to "
 
3511
                         "the master branch until a normal commit "
 
3512
                         "is performed."
 
3513
                    ),
 
3514
             Option('show-diff', short_name='p',
 
3515
                    help='When no message is supplied, show the diff along'
 
3516
                    ' with the status summary in the message editor.'),
 
3517
             Option('lossy', 
 
3518
                    help='When committing to a foreign version control '
 
3519
                    'system do not push data that can not be natively '
 
3520
                    'represented.'),
 
3521
             ]
 
3522
    aliases = ['ci', 'checkin']
 
3523
 
 
3524
    def _iter_bug_fix_urls(self, fixes, branch):
 
3525
        default_bugtracker  = None
 
3526
        # Configure the properties for bug fixing attributes.
 
3527
        for fixed_bug in fixes:
 
3528
            tokens = fixed_bug.split(':')
 
3529
            if len(tokens) == 1:
 
3530
                if default_bugtracker is None:
 
3531
                    branch_config = branch.get_config_stack()
 
3532
                    default_bugtracker = branch_config.get(
 
3533
                        "bugtracker")
 
3534
                if default_bugtracker is None:
 
3535
                    raise errors.BzrCommandError(gettext(
 
3536
                        "No tracker specified for bug %s. Use the form "
 
3537
                        "'tracker:id' or specify a default bug tracker "
 
3538
                        "using the `bugtracker` option.\nSee "
 
3539
                        "\"brz help bugs\" for more information on this "
 
3540
                        "feature. Commit refused.") % fixed_bug)
 
3541
                tag = default_bugtracker
 
3542
                bug_id = tokens[0]
 
3543
            elif len(tokens) != 2:
 
3544
                raise errors.BzrCommandError(gettext(
 
3545
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
 
3546
                    "See \"brz help bugs\" for more information on this "
 
3547
                    "feature.\nCommit refused.") % fixed_bug)
 
3548
            else:
 
3549
                tag, bug_id = tokens
 
3550
            try:
 
3551
                yield bugtracker.get_bug_url(tag, branch, bug_id)
 
3552
            except errors.UnknownBugTrackerAbbreviation:
 
3553
                raise errors.BzrCommandError(gettext(
 
3554
                    'Unrecognized bug %s. Commit refused.') % fixed_bug)
 
3555
            except errors.MalformedBugIdentifier as e:
 
3556
                raise errors.BzrCommandError(gettext(
 
3557
                    "%s\nCommit refused.") % (str(e),))
 
3558
 
 
3559
    def run(self, message=None, file=None, verbose=False, selected_list=None,
 
3560
            unchanged=False, strict=False, local=False, fixes=None,
 
3561
            author=None, show_diff=False, exclude=None, commit_time=None,
 
3562
            lossy=False):
 
3563
        from .errors import (
 
3564
            PointlessCommit,
 
3565
            ConflictsInTree,
 
3566
            StrictCommitFailed
 
3567
        )
 
3568
        from .msgeditor import (
 
3569
            edit_commit_message_encoded,
 
3570
            generate_commit_message_template,
 
3571
            make_commit_message_template_encoded,
 
3572
            set_commit_message,
 
3573
        )
 
3574
 
 
3575
        commit_stamp = offset = None
 
3576
        if commit_time is not None:
 
3577
            try:
 
3578
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
 
3579
            except ValueError as e:
 
3580
                raise errors.BzrCommandError(gettext(
 
3581
                    "Could not parse --commit-time: " + str(e)))
 
3582
 
 
3583
        properties = {}
 
3584
 
 
3585
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
3586
        if selected_list == ['']:
 
3587
            # workaround - commit of root of tree should be exactly the same
 
3588
            # as just default commit in that tree, and succeed even though
 
3589
            # selected-file merge commit is not done yet
 
3590
            selected_list = []
 
3591
 
 
3592
        if fixes is None:
 
3593
            fixes = []
 
3594
        bug_property = bugtracker.encode_fixes_bug_urls(
 
3595
            self._iter_bug_fix_urls(fixes, tree.branch))
 
3596
        if bug_property:
 
3597
            properties['bugs'] = bug_property
 
3598
 
 
3599
        if local and not tree.branch.get_bound_location():
 
3600
            raise errors.LocalRequiresBoundBranch()
 
3601
 
 
3602
        if message is not None:
 
3603
            try:
 
3604
                file_exists = osutils.lexists(message)
 
3605
            except UnicodeError:
 
3606
                # The commit message contains unicode characters that can't be
 
3607
                # represented in the filesystem encoding, so that can't be a
 
3608
                # file.
 
3609
                file_exists = False
 
3610
            if file_exists:
 
3611
                warning_msg = (
 
3612
                    'The commit message is a file name: "%(f)s".\n'
 
3613
                    '(use --file "%(f)s" to take commit message from that file)'
 
3614
                    % { 'f': message })
 
3615
                ui.ui_factory.show_warning(warning_msg)
 
3616
            if '\r' in message:
 
3617
                message = message.replace('\r\n', '\n')
 
3618
                message = message.replace('\r', '\n')
 
3619
            if file:
 
3620
                raise errors.BzrCommandError(gettext(
 
3621
                    "please specify either --message or --file"))
 
3622
 
 
3623
        def get_message(commit_obj):
 
3624
            """Callback to get commit message"""
 
3625
            if file:
 
3626
                f = open(file)
 
3627
                try:
 
3628
                    my_message = f.read().decode(osutils.get_user_encoding())
 
3629
                finally:
 
3630
                    f.close()
 
3631
            elif message is not None:
 
3632
                my_message = message
 
3633
            else:
 
3634
                # No message supplied: make one up.
 
3635
                # text is the status of the tree
 
3636
                text = make_commit_message_template_encoded(tree,
 
3637
                        selected_list, diff=show_diff,
 
3638
                        output_encoding=osutils.get_user_encoding())
 
3639
                # start_message is the template generated from hooks
 
3640
                # XXX: Warning - looks like hooks return unicode,
 
3641
                # make_commit_message_template_encoded returns user encoding.
 
3642
                # We probably want to be using edit_commit_message instead to
 
3643
                # avoid this.
 
3644
                my_message = set_commit_message(commit_obj)
 
3645
                if my_message is None:
 
3646
                    start_message = generate_commit_message_template(commit_obj)
 
3647
                    my_message = edit_commit_message_encoded(text,
 
3648
                        start_message=start_message)
 
3649
                if my_message is None:
 
3650
                    raise errors.BzrCommandError(gettext("please specify a commit"
 
3651
                        " message with either --message or --file"))
 
3652
                if my_message == "":
 
3653
                    raise errors.BzrCommandError(gettext("Empty commit message specified."
 
3654
                            " Please specify a commit message with either"
 
3655
                            " --message or --file or leave a blank message"
 
3656
                            " with --message \"\"."))
 
3657
            return my_message
 
3658
 
 
3659
        # The API permits a commit with a filter of [] to mean 'select nothing'
 
3660
        # but the command line should not do that.
 
3661
        if not selected_list:
 
3662
            selected_list = None
 
3663
        try:
 
3664
            tree.commit(message_callback=get_message,
 
3665
                        specific_files=selected_list,
 
3666
                        allow_pointless=unchanged, strict=strict, local=local,
 
3667
                        reporter=None, verbose=verbose, revprops=properties,
 
3668
                        authors=author, timestamp=commit_stamp,
 
3669
                        timezone=offset,
 
3670
                        exclude=tree.safe_relpath_files(exclude),
 
3671
                        lossy=lossy)
 
3672
        except PointlessCommit:
 
3673
            raise errors.BzrCommandError(gettext("No changes to commit."
 
3674
                " Please 'brz add' the files you want to commit, or use"
 
3675
                " --unchanged to force an empty commit."))
 
3676
        except ConflictsInTree:
 
3677
            raise errors.BzrCommandError(gettext('Conflicts detected in working '
 
3678
                'tree.  Use "brz conflicts" to list, "brz resolve FILE" to'
 
3679
                ' resolve.'))
 
3680
        except StrictCommitFailed:
 
3681
            raise errors.BzrCommandError(gettext("Commit refused because there are"
 
3682
                              " unknown files in the working tree."))
 
3683
        except errors.BoundBranchOutOfDate as e:
 
3684
            e.extra_help = (gettext("\n"
 
3685
                'To commit to master branch, run update and then commit.\n'
 
3686
                'You can also pass --local to commit to continue working '
 
3687
                'disconnected.'))
 
3688
            raise
 
3689
 
 
3690
 
 
3691
class cmd_check(Command):
 
3692
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3693
 
 
3694
    This command checks various invariants about branch and repository storage
 
3695
    to detect data corruption or brz bugs.
 
3696
 
 
3697
    The working tree and branch checks will only give output if a problem is
 
3698
    detected. The output fields of the repository check are:
 
3699
 
 
3700
    revisions
 
3701
        This is just the number of revisions checked.  It doesn't
 
3702
        indicate a problem.
 
3703
 
 
3704
    versionedfiles
 
3705
        This is just the number of versionedfiles checked.  It
 
3706
        doesn't indicate a problem.
 
3707
 
 
3708
    unreferenced ancestors
 
3709
        Texts that are ancestors of other texts, but
 
3710
        are not properly referenced by the revision ancestry.  This is a
 
3711
        subtle problem that Bazaar can work around.
 
3712
 
 
3713
    unique file texts
 
3714
        This is the total number of unique file contents
 
3715
        seen in the checked revisions.  It does not indicate a problem.
 
3716
 
 
3717
    repeated file texts
 
3718
        This is the total number of repeated texts seen
 
3719
        in the checked revisions.  Texts can be repeated when their file
 
3720
        entries are modified, but the file contents are not.  It does not
 
3721
        indicate a problem.
 
3722
 
 
3723
    If no restrictions are specified, all Bazaar data that is found at the given
 
3724
    location will be checked.
 
3725
 
 
3726
    :Examples:
 
3727
 
 
3728
        Check the tree and branch at 'foo'::
 
3729
 
 
3730
            brz check --tree --branch foo
 
3731
 
 
3732
        Check only the repository at 'bar'::
 
3733
 
 
3734
            brz check --repo bar
 
3735
 
 
3736
        Check everything at 'baz'::
 
3737
 
 
3738
            brz check baz
 
3739
    """
 
3740
 
 
3741
    _see_also = ['reconcile']
 
3742
    takes_args = ['path?']
 
3743
    takes_options = ['verbose',
 
3744
                     Option('branch', help="Check the branch related to the"
 
3745
                                           " current directory."),
 
3746
                     Option('repo', help="Check the repository related to the"
 
3747
                                         " current directory."),
 
3748
                     Option('tree', help="Check the working tree related to"
 
3749
                                         " the current directory.")]
 
3750
 
 
3751
    def run(self, path=None, verbose=False, branch=False, repo=False,
 
3752
            tree=False):
 
3753
        from .check import check_dwim
 
3754
        if path is None:
 
3755
            path = '.'
 
3756
        if not branch and not repo and not tree:
 
3757
            branch = repo = tree = True
 
3758
        check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
 
3759
 
 
3760
 
 
3761
class cmd_upgrade(Command):
 
3762
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
 
3763
 
 
3764
    When the default format has changed after a major new release of
 
3765
    Bazaar, you may be informed during certain operations that you
 
3766
    should upgrade. Upgrading to a newer format may improve performance
 
3767
    or make new features available. It may however limit interoperability
 
3768
    with older repositories or with older versions of Bazaar.
 
3769
 
 
3770
    If you wish to upgrade to a particular format rather than the
 
3771
    current default, that can be specified using the --format option.
 
3772
    As a consequence, you can use the upgrade command this way to
 
3773
    "downgrade" to an earlier format, though some conversions are
 
3774
    a one way process (e.g. changing from the 1.x default to the
 
3775
    2.x default) so downgrading is not always possible.
 
3776
 
 
3777
    A backup.bzr.~#~ directory is created at the start of the conversion
 
3778
    process (where # is a number). By default, this is left there on
 
3779
    completion. If the conversion fails, delete the new .bzr directory
 
3780
    and rename this one back in its place. Use the --clean option to ask
 
3781
    for the backup.bzr directory to be removed on successful conversion.
 
3782
    Alternatively, you can delete it by hand if everything looks good
 
3783
    afterwards.
 
3784
 
 
3785
    If the location given is a shared repository, dependent branches
 
3786
    are also converted provided the repository converts successfully.
 
3787
    If the conversion of a branch fails, remaining branches are still
 
3788
    tried.
 
3789
 
 
3790
    For more information on upgrades, see the Bazaar Upgrade Guide,
 
3791
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
 
3792
    """
 
3793
 
 
3794
    _see_also = ['check', 'reconcile', 'formats']
 
3795
    takes_args = ['url?']
 
3796
    takes_options = [
 
3797
        RegistryOption('format',
 
3798
            help='Upgrade to a specific format.  See "brz help'
 
3799
                 ' formats" for details.',
 
3800
            lazy_registry=('breezy.controldir', 'format_registry'),
 
3801
            converter=lambda name: controldir.format_registry.make_controldir(name),
 
3802
            value_switches=True, title='Branch format'),
 
3803
        Option('clean',
 
3804
            help='Remove the backup.bzr directory if successful.'),
 
3805
        Option('dry-run',
 
3806
            help="Show what would be done, but don't actually do anything."),
 
3807
    ]
 
3808
 
 
3809
    def run(self, url='.', format=None, clean=False, dry_run=False):
 
3810
        from .upgrade import upgrade
 
3811
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
 
3812
        if exceptions:
 
3813
            if len(exceptions) == 1:
 
3814
                # Compatibility with historical behavior
 
3815
                raise exceptions[0]
 
3816
            else:
 
3817
                return 3
 
3818
 
 
3819
 
 
3820
class cmd_whoami(Command):
 
3821
    __doc__ = """Show or set brz user id.
 
3822
 
 
3823
    :Examples:
 
3824
        Show the email of the current user::
 
3825
 
 
3826
            brz whoami --email
 
3827
 
 
3828
        Set the current user::
 
3829
 
 
3830
            brz whoami "Frank Chu <fchu@example.com>"
 
3831
    """
 
3832
    takes_options = [ 'directory',
 
3833
                      Option('email',
 
3834
                             help='Display email address only.'),
 
3835
                      Option('branch',
 
3836
                             help='Set identity for the current branch instead of '
 
3837
                                  'globally.'),
 
3838
                    ]
 
3839
    takes_args = ['name?']
 
3840
    encoding_type = 'replace'
 
3841
 
 
3842
    @display_command
 
3843
    def run(self, email=False, branch=False, name=None, directory=None):
 
3844
        if name is None:
 
3845
            if directory is None:
 
3846
                # use branch if we're inside one; otherwise global config
 
3847
                try:
 
3848
                    c = Branch.open_containing(u'.')[0].get_config_stack()
 
3849
                except errors.NotBranchError:
 
3850
                    c = _mod_config.GlobalStack()
 
3851
            else:
 
3852
                c = Branch.open(directory).get_config_stack()
 
3853
            identity = c.get('email')
 
3854
            if email:
 
3855
                self.outf.write(_mod_config.extract_email_address(identity)
 
3856
                                + '\n')
 
3857
            else:
 
3858
                self.outf.write(identity + '\n')
 
3859
            return
 
3860
 
 
3861
        if email:
 
3862
            raise errors.BzrCommandError(gettext("--email can only be used to display existing "
 
3863
                                         "identity"))
 
3864
 
 
3865
        # display a warning if an email address isn't included in the given name.
 
3866
        try:
 
3867
            _mod_config.extract_email_address(name)
 
3868
        except errors.NoEmailInUsername as e:
 
3869
            warning('"%s" does not seem to contain an email address.  '
 
3870
                    'This is allowed, but not recommended.', name)
 
3871
 
 
3872
        # use global config unless --branch given
 
3873
        if branch:
 
3874
            if directory is None:
 
3875
                c = Branch.open_containing(u'.')[0].get_config_stack()
 
3876
            else:
 
3877
                b = Branch.open(directory)
 
3878
                self.add_cleanup(b.lock_write().unlock)
 
3879
                c = b.get_config_stack()
 
3880
        else:
 
3881
            c = _mod_config.GlobalStack()
 
3882
        c.set('email', name)
 
3883
 
 
3884
 
 
3885
class cmd_nick(Command):
 
3886
    __doc__ = """Print or set the branch nickname.
 
3887
 
 
3888
    If unset, the colocated branch name is used for colocated branches, and
 
3889
    the branch directory name is used for other branches.  To print the
 
3890
    current nickname, execute with no argument.
 
3891
 
 
3892
    Bound branches use the nickname of its master branch unless it is set
 
3893
    locally.
 
3894
    """
 
3895
 
 
3896
    _see_also = ['info']
 
3897
    takes_args = ['nickname?']
 
3898
    takes_options = ['directory']
 
3899
    def run(self, nickname=None, directory=u'.'):
 
3900
        branch = Branch.open_containing(directory)[0]
 
3901
        if nickname is None:
 
3902
            self.printme(branch)
 
3903
        else:
 
3904
            branch.nick = nickname
 
3905
 
 
3906
    @display_command
 
3907
    def printme(self, branch):
 
3908
        self.outf.write('%s\n' % branch.nick)
 
3909
 
 
3910
 
 
3911
class cmd_alias(Command):
 
3912
    __doc__ = """Set/unset and display aliases.
 
3913
 
 
3914
    :Examples:
 
3915
        Show the current aliases::
 
3916
 
 
3917
            brz alias
 
3918
 
 
3919
        Show the alias specified for 'll'::
 
3920
 
 
3921
            brz alias ll
 
3922
 
 
3923
        Set an alias for 'll'::
 
3924
 
 
3925
            brz alias ll="log --line -r-10..-1"
 
3926
 
 
3927
        To remove an alias for 'll'::
 
3928
 
 
3929
            brz alias --remove ll
 
3930
 
 
3931
    """
 
3932
    takes_args = ['name?']
 
3933
    takes_options = [
 
3934
        Option('remove', help='Remove the alias.'),
 
3935
        ]
 
3936
 
 
3937
    def run(self, name=None, remove=False):
 
3938
        if remove:
 
3939
            self.remove_alias(name)
 
3940
        elif name is None:
 
3941
            self.print_aliases()
 
3942
        else:
 
3943
            equal_pos = name.find('=')
 
3944
            if equal_pos == -1:
 
3945
                self.print_alias(name)
 
3946
            else:
 
3947
                self.set_alias(name[:equal_pos], name[equal_pos+1:])
 
3948
 
 
3949
    def remove_alias(self, alias_name):
 
3950
        if alias_name is None:
 
3951
            raise errors.BzrCommandError(gettext(
 
3952
                'brz alias --remove expects an alias to remove.'))
 
3953
        # If alias is not found, print something like:
 
3954
        # unalias: foo: not found
 
3955
        c = _mod_config.GlobalConfig()
 
3956
        c.unset_alias(alias_name)
 
3957
 
 
3958
    @display_command
 
3959
    def print_aliases(self):
 
3960
        """Print out the defined aliases in a similar format to bash."""
 
3961
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3962
        for key, value in sorted(viewitems(aliases)):
 
3963
            self.outf.write('brz alias %s="%s"\n' % (key, value))
 
3964
 
 
3965
    @display_command
 
3966
    def print_alias(self, alias_name):
 
3967
        from .commands import get_alias
 
3968
        alias = get_alias(alias_name)
 
3969
        if alias is None:
 
3970
            self.outf.write("brz alias: %s: not found\n" % alias_name)
 
3971
        else:
 
3972
            self.outf.write(
 
3973
                'brz alias %s="%s"\n' % (alias_name, ' '.join(alias)))
 
3974
 
 
3975
    def set_alias(self, alias_name, alias_command):
 
3976
        """Save the alias in the global config."""
 
3977
        c = _mod_config.GlobalConfig()
 
3978
        c.set_alias(alias_name, alias_command)
 
3979
 
 
3980
 
 
3981
class cmd_selftest(Command):
 
3982
    __doc__ = """Run internal test suite.
 
3983
 
 
3984
    If arguments are given, they are regular expressions that say which tests
 
3985
    should run.  Tests matching any expression are run, and other tests are
 
3986
    not run.
 
3987
 
 
3988
    Alternatively if --first is given, matching tests are run first and then
 
3989
    all other tests are run.  This is useful if you have been working in a
 
3990
    particular area, but want to make sure nothing else was broken.
 
3991
 
 
3992
    If --exclude is given, tests that match that regular expression are
 
3993
    excluded, regardless of whether they match --first or not.
 
3994
 
 
3995
    To help catch accidential dependencies between tests, the --randomize
 
3996
    option is useful. In most cases, the argument used is the word 'now'.
 
3997
    Note that the seed used for the random number generator is displayed
 
3998
    when this option is used. The seed can be explicitly passed as the
 
3999
    argument to this option if required. This enables reproduction of the
 
4000
    actual ordering used if and when an order sensitive problem is encountered.
 
4001
 
 
4002
    If --list-only is given, the tests that would be run are listed. This is
 
4003
    useful when combined with --first, --exclude and/or --randomize to
 
4004
    understand their impact. The test harness reports "Listed nn tests in ..."
 
4005
    instead of "Ran nn tests in ..." when list mode is enabled.
 
4006
 
 
4007
    If the global option '--no-plugins' is given, plugins are not loaded
 
4008
    before running the selftests.  This has two effects: features provided or
 
4009
    modified by plugins will not be tested, and tests provided by plugins will
 
4010
    not be run.
 
4011
 
 
4012
    Tests that need working space on disk use a common temporary directory,
 
4013
    typically inside $TMPDIR or /tmp.
 
4014
 
 
4015
    If you set BRZ_TEST_PDB=1 when running selftest, failing tests will drop
 
4016
    into a pdb postmortem session.
 
4017
 
 
4018
    The --coverage=DIRNAME global option produces a report with covered code
 
4019
    indicated.
 
4020
 
 
4021
    :Examples:
 
4022
        Run only tests relating to 'ignore'::
 
4023
 
 
4024
            brz selftest ignore
 
4025
 
 
4026
        Disable plugins and list tests as they're run::
 
4027
 
 
4028
            brz --no-plugins selftest -v
 
4029
    """
 
4030
    # NB: this is used from the class without creating an instance, which is
 
4031
    # why it does not have a self parameter.
 
4032
    def get_transport_type(typestring):
 
4033
        """Parse and return a transport specifier."""
 
4034
        if typestring == "sftp":
 
4035
            from .tests import stub_sftp
 
4036
            return stub_sftp.SFTPAbsoluteServer
 
4037
        elif typestring == "memory":
 
4038
            from .tests import test_server
 
4039
            return memory.MemoryServer
 
4040
        elif typestring == "fakenfs":
 
4041
            from .tests import test_server
 
4042
            return test_server.FakeNFSServer
 
4043
        msg = "No known transport type %s. Supported types are: sftp\n" %\
 
4044
            (typestring)
 
4045
        raise errors.BzrCommandError(msg)
 
4046
 
 
4047
    hidden = True
 
4048
    takes_args = ['testspecs*']
 
4049
    takes_options = ['verbose',
 
4050
                     Option('one',
 
4051
                             help='Stop when one test fails.',
 
4052
                             short_name='1',
 
4053
                             ),
 
4054
                     Option('transport',
 
4055
                            help='Use a different transport by default '
 
4056
                                 'throughout the test suite.',
 
4057
                            type=get_transport_type),
 
4058
                     Option('benchmark',
 
4059
                            help='Run the benchmarks rather than selftests.',
 
4060
                            hidden=True),
 
4061
                     Option('lsprof-timed',
 
4062
                            help='Generate lsprof output for benchmarked'
 
4063
                                 ' sections of code.'),
 
4064
                     Option('lsprof-tests',
 
4065
                            help='Generate lsprof output for each test.'),
 
4066
                     Option('first',
 
4067
                            help='Run all tests, but run specified tests first.',
 
4068
                            short_name='f',
 
4069
                            ),
 
4070
                     Option('list-only',
 
4071
                            help='List the tests instead of running them.'),
 
4072
                     RegistryOption('parallel',
 
4073
                        help="Run the test suite in parallel.",
 
4074
                        lazy_registry=('breezy.tests', 'parallel_registry'),
 
4075
                        value_switches=False,
 
4076
                        ),
 
4077
                     Option('randomize', type=str, argname="SEED",
 
4078
                            help='Randomize the order of tests using the given'
 
4079
                                 ' seed or "now" for the current time.'),
 
4080
                     ListOption('exclude', type=str, argname="PATTERN",
 
4081
                                short_name='x',
 
4082
                                help='Exclude tests that match this regular'
 
4083
                                ' expression.'),
 
4084
                     Option('subunit',
 
4085
                        help='Output test progress via subunit.'),
 
4086
                     Option('strict', help='Fail on missing dependencies or '
 
4087
                            'known failures.'),
 
4088
                     Option('load-list', type=str, argname='TESTLISTFILE',
 
4089
                            help='Load a test id list from a text file.'),
 
4090
                     ListOption('debugflag', type=str, short_name='E',
 
4091
                                help='Turn on a selftest debug flag.'),
 
4092
                     ListOption('starting-with', type=str, argname='TESTID',
 
4093
                                param_name='starting_with', short_name='s',
 
4094
                                help=
 
4095
                                'Load only the tests starting with TESTID.'),
 
4096
                     Option('sync',
 
4097
                            help="By default we disable fsync and fdatasync"
 
4098
                                 " while running the test suite.")
 
4099
                     ]
 
4100
    encoding_type = 'replace'
 
4101
 
 
4102
    def __init__(self):
 
4103
        Command.__init__(self)
 
4104
        self.additional_selftest_args = {}
 
4105
 
 
4106
    def run(self, testspecs_list=None, verbose=False, one=False,
 
4107
            transport=None, benchmark=None,
 
4108
            lsprof_timed=None,
 
4109
            first=False, list_only=False,
 
4110
            randomize=None, exclude=None, strict=False,
 
4111
            load_list=None, debugflag=None, starting_with=None, subunit=False,
 
4112
            parallel=None, lsprof_tests=False,
 
4113
            sync=False):
 
4114
 
 
4115
        # During selftest, disallow proxying, as it can cause severe
 
4116
        # performance penalties and is only needed for thread
 
4117
        # safety. The selftest command is assumed to not use threads
 
4118
        # too heavily. The call should be as early as possible, as
 
4119
        # error reporting for past duplicate imports won't have useful
 
4120
        # backtraces.
 
4121
        lazy_import.disallow_proxying()
 
4122
 
 
4123
        from . import tests
 
4124
 
 
4125
        if testspecs_list is not None:
 
4126
            pattern = '|'.join(testspecs_list)
 
4127
        else:
 
4128
            pattern = ".*"
 
4129
        if subunit:
 
4130
            try:
 
4131
                from .tests import SubUnitBzrRunner
 
4132
            except ImportError:
 
4133
                raise errors.BzrCommandError(gettext("subunit not available. subunit "
 
4134
                    "needs to be installed to use --subunit."))
 
4135
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
 
4136
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
 
4137
            # stdout, which would corrupt the subunit stream. 
 
4138
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
4139
            # following code can be deleted when it's sufficiently deployed
 
4140
            # -- vila/mgz 20100514
 
4141
            if (sys.platform == "win32"
 
4142
                and getattr(sys.stdout, 'fileno', None) is not None):
 
4143
                import msvcrt
 
4144
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
 
4145
        if parallel:
 
4146
            self.additional_selftest_args.setdefault(
 
4147
                'suite_decorators', []).append(parallel)
 
4148
        if benchmark:
 
4149
            raise errors.BzrCommandError(gettext(
 
4150
                "--benchmark is no longer supported from brz 2.2; "
 
4151
                "use bzr-usertest instead"))
 
4152
        test_suite_factory = None
 
4153
        if not exclude:
 
4154
            exclude_pattern = None
 
4155
        else:
 
4156
            exclude_pattern = '(' + '|'.join(exclude) + ')'
 
4157
        if not sync:
 
4158
            self._disable_fsync()
 
4159
        selftest_kwargs = {"verbose": verbose,
 
4160
                          "pattern": pattern,
 
4161
                          "stop_on_failure": one,
 
4162
                          "transport": transport,
 
4163
                          "test_suite_factory": test_suite_factory,
 
4164
                          "lsprof_timed": lsprof_timed,
 
4165
                          "lsprof_tests": lsprof_tests,
 
4166
                          "matching_tests_first": first,
 
4167
                          "list_only": list_only,
 
4168
                          "random_seed": randomize,
 
4169
                          "exclude_pattern": exclude_pattern,
 
4170
                          "strict": strict,
 
4171
                          "load_list": load_list,
 
4172
                          "debug_flags": debugflag,
 
4173
                          "starting_with": starting_with
 
4174
                          }
 
4175
        selftest_kwargs.update(self.additional_selftest_args)
 
4176
 
 
4177
        # Make deprecation warnings visible, unless -Werror is set
 
4178
        cleanup = symbol_versioning.activate_deprecation_warnings(
 
4179
            override=False)
 
4180
        try:
 
4181
            result = tests.selftest(**selftest_kwargs)
 
4182
        finally:
 
4183
            cleanup()
 
4184
        return int(not result)
 
4185
 
 
4186
    def _disable_fsync(self):
 
4187
        """Change the 'os' functionality to not synchronize."""
 
4188
        self._orig_fsync = getattr(os, 'fsync', None)
 
4189
        if self._orig_fsync is not None:
 
4190
            os.fsync = lambda filedes: None
 
4191
        self._orig_fdatasync = getattr(os, 'fdatasync', None)
 
4192
        if self._orig_fdatasync is not None:
 
4193
            os.fdatasync = lambda filedes: None
 
4194
 
 
4195
 
 
4196
class cmd_version(Command):
 
4197
    __doc__ = """Show version of brz."""
 
4198
 
 
4199
    encoding_type = 'replace'
 
4200
    takes_options = [
 
4201
        Option("short", help="Print just the version number."),
 
4202
        ]
 
4203
 
 
4204
    @display_command
 
4205
    def run(self, short=False):
 
4206
        from .version import show_version
 
4207
        if short:
 
4208
            self.outf.write(breezy.version_string + '\n')
 
4209
        else:
 
4210
            show_version(to_file=self.outf)
 
4211
 
 
4212
 
 
4213
class cmd_rocks(Command):
 
4214
    __doc__ = """Statement of optimism."""
 
4215
 
 
4216
    hidden = True
 
4217
 
 
4218
    @display_command
 
4219
    def run(self):
 
4220
        self.outf.write(gettext("It sure does!\n"))
 
4221
 
 
4222
 
 
4223
class cmd_find_merge_base(Command):
 
4224
    __doc__ = """Find and print a base revision for merging two branches."""
 
4225
    # TODO: Options to specify revisions on either side, as if
 
4226
    #       merging only part of the history.
 
4227
    takes_args = ['branch', 'other']
 
4228
    hidden = True
 
4229
 
 
4230
    @display_command
 
4231
    def run(self, branch, other):
 
4232
        from .revision import ensure_null
 
4233
 
 
4234
        branch1 = Branch.open_containing(branch)[0]
 
4235
        branch2 = Branch.open_containing(other)[0]
 
4236
        self.add_cleanup(branch1.lock_read().unlock)
 
4237
        self.add_cleanup(branch2.lock_read().unlock)
 
4238
        last1 = ensure_null(branch1.last_revision())
 
4239
        last2 = ensure_null(branch2.last_revision())
 
4240
 
 
4241
        graph = branch1.repository.get_graph(branch2.repository)
 
4242
        base_rev_id = graph.find_unique_lca(last1, last2)
 
4243
 
 
4244
        self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
 
4245
 
 
4246
 
 
4247
class cmd_merge(Command):
 
4248
    __doc__ = """Perform a three-way merge.
 
4249
 
 
4250
    The source of the merge can be specified either in the form of a branch,
 
4251
    or in the form of a path to a file containing a merge directive generated
 
4252
    with brz send. If neither is specified, the default is the upstream branch
 
4253
    or the branch most recently merged using --remember.  The source of the
 
4254
    merge may also be specified in the form of a path to a file in another
 
4255
    branch:  in this case, only the modifications to that file are merged into
 
4256
    the current working tree.
 
4257
 
 
4258
    When merging from a branch, by default brz will try to merge in all new
 
4259
    work from the other branch, automatically determining an appropriate base
 
4260
    revision.  If this fails, you may need to give an explicit base.
 
4261
 
 
4262
    To pick a different ending revision, pass "--revision OTHER".  brz will
 
4263
    try to merge in all new work up to and including revision OTHER.
 
4264
 
 
4265
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
 
4266
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
 
4267
    causes some revisions to be skipped, i.e. if the destination branch does
 
4268
    not already contain revision BASE, such a merge is commonly referred to as
 
4269
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
 
4270
    cherrypicks. The changes look like a normal commit, and the history of the
 
4271
    changes from the other branch is not stored in the commit.
 
4272
 
 
4273
    Revision numbers are always relative to the source branch.
 
4274
 
 
4275
    Merge will do its best to combine the changes in two branches, but there
 
4276
    are some kinds of problems only a human can fix.  When it encounters those,
 
4277
    it will mark a conflict.  A conflict means that you need to fix something,
 
4278
    before you can commit.
 
4279
 
 
4280
    Use brz resolve when you have fixed a problem.  See also brz conflicts.
 
4281
 
 
4282
    If there is no default branch set, the first merge will set it (use
 
4283
    --no-remember to avoid setting it). After that, you can omit the branch
 
4284
    to use the default.  To change the default, use --remember. The value will
 
4285
    only be saved if the remote location can be accessed.
 
4286
 
 
4287
    The results of the merge are placed into the destination working
 
4288
    directory, where they can be reviewed (with brz diff), tested, and then
 
4289
    committed to record the result of the merge.
 
4290
 
 
4291
    merge refuses to run if there are any uncommitted changes, unless
 
4292
    --force is given.  If --force is given, then the changes from the source 
 
4293
    will be merged with the current working tree, including any uncommitted
 
4294
    changes in the tree.  The --force option can also be used to create a
 
4295
    merge revision which has more than two parents.
 
4296
 
 
4297
    If one would like to merge changes from the working tree of the other
 
4298
    branch without merging any committed revisions, the --uncommitted option
 
4299
    can be given.
 
4300
 
 
4301
    To select only some changes to merge, use "merge -i", which will prompt
 
4302
    you to apply each diff hunk and file change, similar to "shelve".
 
4303
 
 
4304
    :Examples:
 
4305
        To merge all new revisions from brz.dev::
 
4306
 
 
4307
            brz merge ../brz.dev
 
4308
 
 
4309
        To merge changes up to and including revision 82 from brz.dev::
 
4310
 
 
4311
            brz merge -r 82 ../brz.dev
 
4312
 
 
4313
        To merge the changes introduced by 82, without previous changes::
 
4314
 
 
4315
            brz merge -r 81..82 ../brz.dev
 
4316
 
 
4317
        To apply a merge directive contained in /tmp/merge::
 
4318
 
 
4319
            brz merge /tmp/merge
 
4320
 
 
4321
        To create a merge revision with three parents from two branches
 
4322
        feature1a and feature1b:
 
4323
 
 
4324
            brz merge ../feature1a
 
4325
            brz merge ../feature1b --force
 
4326
            brz commit -m 'revision with three parents'
 
4327
    """
 
4328
 
 
4329
    encoding_type = 'exact'
 
4330
    _see_also = ['update', 'remerge', 'status-flags', 'send']
 
4331
    takes_args = ['location?']
 
4332
    takes_options = [
 
4333
        'change',
 
4334
        'revision',
 
4335
        Option('force',
 
4336
               help='Merge even if the destination tree has uncommitted changes.'),
 
4337
        'merge-type',
 
4338
        'reprocess',
 
4339
        'remember',
 
4340
        Option('show-base', help="Show base revision text in "
 
4341
               "conflicts."),
 
4342
        Option('uncommitted', help='Apply uncommitted changes'
 
4343
               ' from a working copy, instead of branch changes.'),
 
4344
        Option('pull', help='If the destination is already'
 
4345
                ' completely merged into the source, pull from the'
 
4346
                ' source rather than merging.  When this happens,'
 
4347
                ' you do not need to commit the result.'),
 
4348
        custom_help('directory',
 
4349
               help='Branch to merge into, '
 
4350
                    'rather than the one containing the working directory.'),
 
4351
        Option('preview', help='Instead of merging, show a diff of the'
 
4352
               ' merge.'),
 
4353
        Option('interactive', help='Select changes interactively.',
 
4354
            short_name='i')
 
4355
    ]
 
4356
 
 
4357
    def run(self, location=None, revision=None, force=False,
 
4358
            merge_type=None, show_base=False, reprocess=None, remember=None,
 
4359
            uncommitted=False, pull=False,
 
4360
            directory=None,
 
4361
            preview=False,
 
4362
            interactive=False,
 
4363
            ):
 
4364
        if merge_type is None:
 
4365
            merge_type = _mod_merge.Merge3Merger
 
4366
 
 
4367
        if directory is None: directory = u'.'
 
4368
        possible_transports = []
 
4369
        merger = None
 
4370
        allow_pending = True
 
4371
        verified = 'inapplicable'
 
4372
 
 
4373
        tree = WorkingTree.open_containing(directory)[0]
 
4374
        if tree.branch.revno() == 0:
 
4375
            raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
 
4376
                                         'https://bugs.launchpad.net/bzr/+bug/308562'))
 
4377
 
 
4378
        try:
 
4379
            basis_tree = tree.revision_tree(tree.last_revision())
 
4380
        except errors.NoSuchRevision:
 
4381
            basis_tree = tree.basis_tree()
 
4382
 
 
4383
        # die as quickly as possible if there are uncommitted changes
 
4384
        if not force:
 
4385
            if tree.has_changes():
 
4386
                raise errors.UncommittedChanges(tree)
 
4387
 
 
4388
        view_info = _get_view_info_for_change_reporter(tree)
 
4389
        change_reporter = delta._ChangeReporter(
 
4390
            unversioned_filter=tree.is_ignored, view_info=view_info)
 
4391
        pb = ui.ui_factory.nested_progress_bar()
 
4392
        self.add_cleanup(pb.finished)
 
4393
        self.add_cleanup(tree.lock_write().unlock)
 
4394
        if location is not None:
 
4395
            try:
 
4396
                mergeable = bundle.read_mergeable_from_url(location,
 
4397
                    possible_transports=possible_transports)
 
4398
            except errors.NotABundle:
 
4399
                mergeable = None
 
4400
            else:
 
4401
                if uncommitted:
 
4402
                    raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
 
4403
                        ' with bundles or merge directives.'))
 
4404
 
 
4405
                if revision is not None:
 
4406
                    raise errors.BzrCommandError(gettext(
 
4407
                        'Cannot use -r with merge directives or bundles'))
 
4408
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
4409
                   mergeable, None)
 
4410
 
 
4411
        if merger is None and uncommitted:
 
4412
            if revision is not None and len(revision) > 0:
 
4413
                raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
 
4414
                    ' --revision at the same time.'))
 
4415
            merger = self.get_merger_from_uncommitted(tree, location, None)
 
4416
            allow_pending = False
 
4417
 
 
4418
        if merger is None:
 
4419
            merger, allow_pending = self._get_merger_from_branch(tree,
 
4420
                location, revision, remember, possible_transports, None)
 
4421
 
 
4422
        merger.merge_type = merge_type
 
4423
        merger.reprocess = reprocess
 
4424
        merger.show_base = show_base
 
4425
        self.sanity_check_merger(merger)
 
4426
        if (merger.base_rev_id == merger.other_rev_id and
 
4427
            merger.other_rev_id is not None):
 
4428
            # check if location is a nonexistent file (and not a branch) to
 
4429
            # disambiguate the 'Nothing to do'
 
4430
            if merger.interesting_files:
 
4431
                if not merger.other_tree.has_filename(
 
4432
                    merger.interesting_files[0]):
 
4433
                    note(gettext("merger: ") + str(merger))
 
4434
                    raise errors.PathsDoNotExist([location])
 
4435
            note(gettext('Nothing to do.'))
 
4436
            return 0
 
4437
        if pull and not preview:
 
4438
            if merger.interesting_files is not None:
 
4439
                raise errors.BzrCommandError(gettext('Cannot pull individual files'))
 
4440
            if (merger.base_rev_id == tree.last_revision()):
 
4441
                result = tree.pull(merger.other_branch, False,
 
4442
                                   merger.other_rev_id)
 
4443
                result.report(self.outf)
 
4444
                return 0
 
4445
        if merger.this_basis is None:
 
4446
            raise errors.BzrCommandError(gettext(
 
4447
                "This branch has no commits."
 
4448
                " (perhaps you would prefer 'brz pull')"))
 
4449
        if preview:
 
4450
            return self._do_preview(merger)
 
4451
        elif interactive:
 
4452
            return self._do_interactive(merger)
 
4453
        else:
 
4454
            return self._do_merge(merger, change_reporter, allow_pending,
 
4455
                                  verified)
 
4456
 
 
4457
    def _get_preview(self, merger):
 
4458
        tree_merger = merger.make_merger()
 
4459
        tt = tree_merger.make_preview_transform()
 
4460
        self.add_cleanup(tt.finalize)
 
4461
        result_tree = tt.get_preview_tree()
 
4462
        return result_tree
 
4463
 
 
4464
    def _do_preview(self, merger):
 
4465
        from .diff import show_diff_trees
 
4466
        result_tree = self._get_preview(merger)
 
4467
        path_encoding = osutils.get_diff_header_encoding()
 
4468
        show_diff_trees(merger.this_tree, result_tree, self.outf,
 
4469
                        old_label='', new_label='',
 
4470
                        path_encoding=path_encoding)
 
4471
 
 
4472
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
 
4473
        merger.change_reporter = change_reporter
 
4474
        conflict_count = merger.do_merge()
 
4475
        if allow_pending:
 
4476
            merger.set_pending()
 
4477
        if verified == 'failed':
 
4478
            warning('Preview patch does not match changes')
 
4479
        if conflict_count != 0:
 
4480
            return 1
 
4481
        else:
 
4482
            return 0
 
4483
 
 
4484
    def _do_interactive(self, merger):
 
4485
        """Perform an interactive merge.
 
4486
 
 
4487
        This works by generating a preview tree of the merge, then using
 
4488
        Shelver to selectively remove the differences between the working tree
 
4489
        and the preview tree.
 
4490
        """
 
4491
        from . import shelf_ui
 
4492
        result_tree = self._get_preview(merger)
 
4493
        writer = breezy.option.diff_writer_registry.get()
 
4494
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
 
4495
                                   reporter=shelf_ui.ApplyReporter(),
 
4496
                                   diff_writer=writer(sys.stdout))
 
4497
        try:
 
4498
            shelver.run()
 
4499
        finally:
 
4500
            shelver.finalize()
 
4501
 
 
4502
    def sanity_check_merger(self, merger):
 
4503
        if (merger.show_base and
 
4504
            not merger.merge_type is _mod_merge.Merge3Merger):
 
4505
            raise errors.BzrCommandError(gettext("Show-base is not supported for this"
 
4506
                                         " merge type. %s") % merger.merge_type)
 
4507
        if merger.reprocess is None:
 
4508
            if merger.show_base:
 
4509
                merger.reprocess = False
 
4510
            else:
 
4511
                # Use reprocess if the merger supports it
 
4512
                merger.reprocess = merger.merge_type.supports_reprocess
 
4513
        if merger.reprocess and not merger.merge_type.supports_reprocess:
 
4514
            raise errors.BzrCommandError(gettext("Conflict reduction is not supported"
 
4515
                                         " for merge type %s.") %
 
4516
                                         merger.merge_type)
 
4517
        if merger.reprocess and merger.show_base:
 
4518
            raise errors.BzrCommandError(gettext("Cannot do conflict reduction and"
 
4519
                                         " show base."))
 
4520
 
 
4521
    def _get_merger_from_branch(self, tree, location, revision, remember,
 
4522
                                possible_transports, pb):
 
4523
        """Produce a merger from a location, assuming it refers to a branch."""
 
4524
        # find the branch locations
 
4525
        other_loc, user_location = self._select_branch_location(tree, location,
 
4526
            revision, -1)
 
4527
        if revision is not None and len(revision) == 2:
 
4528
            base_loc, _unused = self._select_branch_location(tree,
 
4529
                location, revision, 0)
 
4530
        else:
 
4531
            base_loc = other_loc
 
4532
        # Open the branches
 
4533
        other_branch, other_path = Branch.open_containing(other_loc,
 
4534
            possible_transports)
 
4535
        if base_loc == other_loc:
 
4536
            base_branch = other_branch
 
4537
        else:
 
4538
            base_branch, base_path = Branch.open_containing(base_loc,
 
4539
                possible_transports)
 
4540
        # Find the revision ids
 
4541
        other_revision_id = None
 
4542
        base_revision_id = None
 
4543
        if revision is not None:
 
4544
            if len(revision) >= 1:
 
4545
                other_revision_id = revision[-1].as_revision_id(other_branch)
 
4546
            if len(revision) == 2:
 
4547
                base_revision_id = revision[0].as_revision_id(base_branch)
 
4548
        if other_revision_id is None:
 
4549
            other_revision_id = _mod_revision.ensure_null(
 
4550
                other_branch.last_revision())
 
4551
        # Remember where we merge from. We need to remember if:
 
4552
        # - user specify a location (and we don't merge from the parent
 
4553
        #   branch)
 
4554
        # - user ask to remember or there is no previous location set to merge
 
4555
        #   from and user didn't ask to *not* remember
 
4556
        if (user_location is not None
 
4557
            and ((remember
 
4558
                  or (remember is None
 
4559
                      and tree.branch.get_submit_branch() is None)))):
 
4560
            tree.branch.set_submit_branch(other_branch.base)
 
4561
        # Merge tags (but don't set them in the master branch yet, the user
 
4562
        # might revert this merge).  Commit will propagate them.
 
4563
        other_branch.tags.merge_to(tree.branch.tags, ignore_master=True)
 
4564
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
 
4565
            other_revision_id, base_revision_id, other_branch, base_branch)
 
4566
        if other_path != '':
 
4567
            allow_pending = False
 
4568
            merger.interesting_files = [other_path]
 
4569
        else:
 
4570
            allow_pending = True
 
4571
        return merger, allow_pending
 
4572
 
 
4573
    def get_merger_from_uncommitted(self, tree, location, pb):
 
4574
        """Get a merger for uncommitted changes.
 
4575
 
 
4576
        :param tree: The tree the merger should apply to.
 
4577
        :param location: The location containing uncommitted changes.
 
4578
        :param pb: The progress bar to use for showing progress.
 
4579
        """
 
4580
        location = self._select_branch_location(tree, location)[0]
 
4581
        other_tree, other_path = WorkingTree.open_containing(location)
 
4582
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
 
4583
        if other_path != '':
 
4584
            merger.interesting_files = [other_path]
 
4585
        return merger
 
4586
 
 
4587
    def _select_branch_location(self, tree, user_location, revision=None,
 
4588
                                index=None):
 
4589
        """Select a branch location, according to possible inputs.
 
4590
 
 
4591
        If provided, branches from ``revision`` are preferred.  (Both
 
4592
        ``revision`` and ``index`` must be supplied.)
 
4593
 
 
4594
        Otherwise, the ``location`` parameter is used.  If it is None, then the
 
4595
        ``submit`` or ``parent`` location is used, and a note is printed.
 
4596
 
 
4597
        :param tree: The working tree to select a branch for merging into
 
4598
        :param location: The location entered by the user
 
4599
        :param revision: The revision parameter to the command
 
4600
        :param index: The index to use for the revision parameter.  Negative
 
4601
            indices are permitted.
 
4602
        :return: (selected_location, user_location).  The default location
 
4603
            will be the user-entered location.
 
4604
        """
 
4605
        if (revision is not None and index is not None
 
4606
            and revision[index] is not None):
 
4607
            branch = revision[index].get_branch()
 
4608
            if branch is not None:
 
4609
                return branch, branch
 
4610
        if user_location is None:
 
4611
            location = self._get_remembered(tree, 'Merging from')
 
4612
        else:
 
4613
            location = user_location
 
4614
        return location, user_location
 
4615
 
 
4616
    def _get_remembered(self, tree, verb_string):
 
4617
        """Use tree.branch's parent if none was supplied.
 
4618
 
 
4619
        Report if the remembered location was used.
 
4620
        """
 
4621
        stored_location = tree.branch.get_submit_branch()
 
4622
        stored_location_type = "submit"
 
4623
        if stored_location is None:
 
4624
            stored_location = tree.branch.get_parent()
 
4625
            stored_location_type = "parent"
 
4626
        mutter("%s", stored_location)
 
4627
        if stored_location is None:
 
4628
            raise errors.BzrCommandError(gettext("No location specified or remembered"))
 
4629
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
 
4630
        note(gettext("{0} remembered {1} location {2}").format(verb_string,
 
4631
                stored_location_type, display_url))
 
4632
        return stored_location
 
4633
 
 
4634
 
 
4635
class cmd_remerge(Command):
 
4636
    __doc__ = """Redo a merge.
 
4637
 
 
4638
    Use this if you want to try a different merge technique while resolving
 
4639
    conflicts.  Some merge techniques are better than others, and remerge
 
4640
    lets you try different ones on different files.
 
4641
 
 
4642
    The options for remerge have the same meaning and defaults as the ones for
 
4643
    merge.  The difference is that remerge can (only) be run when there is a
 
4644
    pending merge, and it lets you specify particular files.
 
4645
 
 
4646
    :Examples:
 
4647
        Re-do the merge of all conflicted files, and show the base text in
 
4648
        conflict regions, in addition to the usual THIS and OTHER texts::
 
4649
 
 
4650
            brz remerge --show-base
 
4651
 
 
4652
        Re-do the merge of "foobar", using the weave merge algorithm, with
 
4653
        additional processing to reduce the size of conflict regions::
 
4654
 
 
4655
            brz remerge --merge-type weave --reprocess foobar
 
4656
    """
 
4657
    takes_args = ['file*']
 
4658
    takes_options = [
 
4659
            'merge-type',
 
4660
            'reprocess',
 
4661
            Option('show-base',
 
4662
                   help="Show base revision text in conflicts."),
 
4663
            ]
 
4664
 
 
4665
    def run(self, file_list=None, merge_type=None, show_base=False,
 
4666
            reprocess=False):
 
4667
        from .conflicts import restore
 
4668
        if merge_type is None:
 
4669
            merge_type = _mod_merge.Merge3Merger
 
4670
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
4671
        self.add_cleanup(tree.lock_write().unlock)
 
4672
        parents = tree.get_parent_ids()
 
4673
        if len(parents) != 2:
 
4674
            raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
 
4675
                                         " merges.  Not cherrypicking or"
 
4676
                                         " multi-merges."))
 
4677
        repository = tree.branch.repository
 
4678
        interesting_ids = None
 
4679
        new_conflicts = []
 
4680
        conflicts = tree.conflicts()
 
4681
        if file_list is not None:
 
4682
            interesting_ids = set()
 
4683
            for filename in file_list:
 
4684
                file_id = tree.path2id(filename)
 
4685
                if file_id is None:
 
4686
                    raise errors.NotVersionedError(filename)
 
4687
                interesting_ids.add(file_id)
 
4688
                if tree.kind(file_id) != "directory":
 
4689
                    continue
 
4690
 
 
4691
                # FIXME: Support nested trees
 
4692
                for name, ie in tree.root_inventory.iter_entries(file_id):
 
4693
                    interesting_ids.add(ie.file_id)
 
4694
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
4695
        else:
 
4696
            # Remerge only supports resolving contents conflicts
 
4697
            allowed_conflicts = ('text conflict', 'contents conflict')
 
4698
            restore_files = [c.path for c in conflicts
 
4699
                             if c.typestring in allowed_conflicts]
 
4700
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
 
4701
        tree.set_conflicts(ConflictList(new_conflicts))
 
4702
        if file_list is not None:
 
4703
            restore_files = file_list
 
4704
        for filename in restore_files:
 
4705
            try:
 
4706
                restore(tree.abspath(filename))
 
4707
            except errors.NotConflicted:
 
4708
                pass
 
4709
        # Disable pending merges, because the file texts we are remerging
 
4710
        # have not had those merges performed.  If we use the wrong parents
 
4711
        # list, we imply that the working tree text has seen and rejected
 
4712
        # all the changes from the other tree, when in fact those changes
 
4713
        # have not yet been seen.
 
4714
        tree.set_parent_ids(parents[:1])
 
4715
        try:
 
4716
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
 
4717
            merger.interesting_ids = interesting_ids
 
4718
            merger.merge_type = merge_type
 
4719
            merger.show_base = show_base
 
4720
            merger.reprocess = reprocess
 
4721
            conflicts = merger.do_merge()
 
4722
        finally:
 
4723
            tree.set_parent_ids(parents)
 
4724
        if conflicts > 0:
 
4725
            return 1
 
4726
        else:
 
4727
            return 0
 
4728
 
 
4729
 
 
4730
class cmd_revert(Command):
 
4731
    __doc__ = """\
 
4732
    Set files in the working tree back to the contents of a previous revision.
 
4733
 
 
4734
    Giving a list of files will revert only those files.  Otherwise, all files
 
4735
    will be reverted.  If the revision is not specified with '--revision', the
 
4736
    working tree basis revision is used. A revert operation affects only the
 
4737
    working tree, not any revision history like the branch and repository or
 
4738
    the working tree basis revision.
 
4739
 
 
4740
    To remove only some changes, without reverting to a prior version, use
 
4741
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
 
4742
    will remove the changes introduced by the second last commit (-2), without
 
4743
    affecting the changes introduced by the last commit (-1).  To remove
 
4744
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
4745
    To update the branch to a specific revision or the latest revision and
 
4746
    update the working tree accordingly while preserving local changes, see the
 
4747
    update command.
 
4748
 
 
4749
    Uncommitted changes to files that are reverted will be discarded.
 
4750
    Howver, by default, any files that have been manually changed will be
 
4751
    backed up first.  (Files changed only by merge are not backed up.)  Backup
 
4752
    files have '.~#~' appended to their name, where # is a number.
 
4753
 
 
4754
    When you provide files, you can use their current pathname or the pathname
 
4755
    from the target revision.  So you can use revert to "undelete" a file by
 
4756
    name.  If you name a directory, all the contents of that directory will be
 
4757
    reverted.
 
4758
 
 
4759
    If you have newly added files since the target revision, they will be
 
4760
    removed.  If the files to be removed have been changed, backups will be
 
4761
    created as above.  Directories containing unknown files will not be
 
4762
    deleted.
 
4763
 
 
4764
    The working tree contains a list of revisions that have been merged but
 
4765
    not yet committed. These revisions will be included as additional parents
 
4766
    of the next commit.  Normally, using revert clears that list as well as
 
4767
    reverting the files.  If any files are specified, revert leaves the list
 
4768
    of uncommitted merges alone and reverts only the files.  Use ``brz revert
 
4769
    .`` in the tree root to revert all files but keep the recorded merges,
 
4770
    and ``brz revert --forget-merges`` to clear the pending merge list without
 
4771
    reverting any files.
 
4772
 
 
4773
    Using "brz revert --forget-merges", it is possible to apply all of the
 
4774
    changes from a branch in a single revision.  To do this, perform the merge
 
4775
    as desired.  Then doing revert with the "--forget-merges" option will keep
 
4776
    the content of the tree as it was, but it will clear the list of pending
 
4777
    merges.  The next commit will then contain all of the changes that are
 
4778
    present in the other branch, but without any other parent revisions.
 
4779
    Because this technique forgets where these changes originated, it may
 
4780
    cause additional conflicts on later merges involving the same source and
 
4781
    target branches.
 
4782
    """
 
4783
 
 
4784
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4785
    takes_options = [
 
4786
        'revision',
 
4787
        Option('no-backup', "Do not save backups of reverted files."),
 
4788
        Option('forget-merges',
 
4789
               'Remove pending merge marker, without changing any files.'),
 
4790
        ]
 
4791
    takes_args = ['file*']
 
4792
 
 
4793
    def run(self, revision=None, no_backup=False, file_list=None,
 
4794
            forget_merges=None):
 
4795
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
4796
        self.add_cleanup(tree.lock_tree_write().unlock)
 
4797
        if forget_merges:
 
4798
            tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4799
        else:
 
4800
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4801
 
 
4802
    @staticmethod
 
4803
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
 
4804
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
 
4805
        tree.revert(file_list, rev_tree, not no_backup, None,
 
4806
            report_changes=True)
 
4807
 
 
4808
 
 
4809
class cmd_assert_fail(Command):
 
4810
    __doc__ = """Test reporting of assertion failures"""
 
4811
    # intended just for use in testing
 
4812
 
 
4813
    hidden = True
 
4814
 
 
4815
    def run(self):
 
4816
        raise AssertionError("always fails")
 
4817
 
 
4818
 
 
4819
class cmd_help(Command):
 
4820
    __doc__ = """Show help on a command or other topic.
 
4821
    """
 
4822
 
 
4823
    _see_also = ['topics']
 
4824
    takes_options = [
 
4825
            Option('long', 'Show help on all commands.'),
 
4826
            ]
 
4827
    takes_args = ['topic?']
 
4828
    aliases = ['?', '--help', '-?', '-h']
 
4829
 
 
4830
    @display_command
 
4831
    def run(self, topic=None, long=False):
 
4832
        import breezy.help
 
4833
        if topic is None and long:
 
4834
            topic = "commands"
 
4835
        breezy.help.help(topic)
 
4836
 
 
4837
 
 
4838
class cmd_shell_complete(Command):
 
4839
    __doc__ = """Show appropriate completions for context.
 
4840
 
 
4841
    For a list of all available commands, say 'brz shell-complete'.
 
4842
    """
 
4843
    takes_args = ['context?']
 
4844
    aliases = ['s-c']
 
4845
    hidden = True
 
4846
 
 
4847
    @display_command
 
4848
    def run(self, context=None):
 
4849
        from . import shellcomplete
 
4850
        shellcomplete.shellcomplete(context)
 
4851
 
 
4852
 
 
4853
class cmd_missing(Command):
 
4854
    __doc__ = """Show unmerged/unpulled revisions between two branches.
 
4855
 
 
4856
    OTHER_BRANCH may be local or remote.
 
4857
 
 
4858
    To filter on a range of revisions, you can use the command -r begin..end
 
4859
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
4860
    also valid.
 
4861
            
 
4862
    :Exit values:
 
4863
        1 - some missing revisions
 
4864
        0 - no missing revisions
 
4865
 
 
4866
    :Examples:
 
4867
 
 
4868
        Determine the missing revisions between this and the branch at the
 
4869
        remembered pull location::
 
4870
 
 
4871
            brz missing
 
4872
 
 
4873
        Determine the missing revisions between this and another branch::
 
4874
 
 
4875
            brz missing http://server/branch
 
4876
 
 
4877
        Determine the missing revisions up to a specific revision on the other
 
4878
        branch::
 
4879
 
 
4880
            brz missing -r ..-10
 
4881
 
 
4882
        Determine the missing revisions up to a specific revision on this
 
4883
        branch::
 
4884
 
 
4885
            brz missing --my-revision ..-10
 
4886
    """
 
4887
 
 
4888
    _see_also = ['merge', 'pull']
 
4889
    takes_args = ['other_branch?']
 
4890
    takes_options = [
 
4891
        'directory',
 
4892
        Option('reverse', 'Reverse the order of revisions.'),
 
4893
        Option('mine-only',
 
4894
               'Display changes in the local branch only.'),
 
4895
        Option('this' , 'Same as --mine-only.'),
 
4896
        Option('theirs-only',
 
4897
               'Display changes in the remote branch only.'),
 
4898
        Option('other', 'Same as --theirs-only.'),
 
4899
        'log-format',
 
4900
        'show-ids',
 
4901
        'verbose',
 
4902
        custom_help('revision',
 
4903
             help='Filter on other branch revisions (inclusive). '
 
4904
                'See "help revisionspec" for details.'),
 
4905
        Option('my-revision',
 
4906
            type=_parse_revision_str,
 
4907
            help='Filter on local branch revisions (inclusive). '
 
4908
                'See "help revisionspec" for details.'),
 
4909
        Option('include-merged',
 
4910
               'Show all revisions in addition to the mainline ones.'),
 
4911
        Option('include-merges', hidden=True,
 
4912
               help='Historical alias for --include-merged.'),
 
4913
        ]
 
4914
    encoding_type = 'replace'
 
4915
 
 
4916
    @display_command
 
4917
    def run(self, other_branch=None, reverse=False, mine_only=False,
 
4918
            theirs_only=False,
 
4919
            log_format=None, long=False, short=False, line=False,
 
4920
            show_ids=False, verbose=False, this=False, other=False,
 
4921
            include_merged=None, revision=None, my_revision=None,
 
4922
            directory=u'.'):
 
4923
        from breezy.missing import find_unmerged, iter_log_revisions
 
4924
        def message(s):
 
4925
            if not is_quiet():
 
4926
                self.outf.write(s)
 
4927
 
 
4928
        if include_merged is None:
 
4929
            include_merged = False
 
4930
        if this:
 
4931
            mine_only = this
 
4932
        if other:
 
4933
            theirs_only = other
 
4934
        # TODO: We should probably check that we don't have mine-only and
 
4935
        #       theirs-only set, but it gets complicated because we also have
 
4936
        #       this and other which could be used.
 
4937
        restrict = 'all'
 
4938
        if mine_only:
 
4939
            restrict = 'local'
 
4940
        elif theirs_only:
 
4941
            restrict = 'remote'
 
4942
 
 
4943
        local_branch = Branch.open_containing(directory)[0]
 
4944
        self.add_cleanup(local_branch.lock_read().unlock)
 
4945
 
 
4946
        parent = local_branch.get_parent()
 
4947
        if other_branch is None:
 
4948
            other_branch = parent
 
4949
            if other_branch is None:
 
4950
                raise errors.BzrCommandError(gettext("No peer location known"
 
4951
                                             " or specified."))
 
4952
            display_url = urlutils.unescape_for_display(parent,
 
4953
                                                        self.outf.encoding)
 
4954
            message(gettext("Using saved parent location: {0}\n").format(
 
4955
                    display_url))
 
4956
 
 
4957
        remote_branch = Branch.open(other_branch)
 
4958
        if remote_branch.base == local_branch.base:
 
4959
            remote_branch = local_branch
 
4960
        else:
 
4961
            self.add_cleanup(remote_branch.lock_read().unlock)
 
4962
 
 
4963
        local_revid_range = _revision_range_to_revid_range(
 
4964
            _get_revision_range(my_revision, local_branch,
 
4965
                self.name()))
 
4966
 
 
4967
        remote_revid_range = _revision_range_to_revid_range(
 
4968
            _get_revision_range(revision,
 
4969
                remote_branch, self.name()))
 
4970
 
 
4971
        local_extra, remote_extra = find_unmerged(
 
4972
            local_branch, remote_branch, restrict,
 
4973
            backward=not reverse,
 
4974
            include_merged=include_merged,
 
4975
            local_revid_range=local_revid_range,
 
4976
            remote_revid_range=remote_revid_range)
 
4977
 
 
4978
        if log_format is None:
 
4979
            registry = log.log_formatter_registry
 
4980
            log_format = registry.get_default(local_branch)
 
4981
        lf = log_format(to_file=self.outf,
 
4982
                        show_ids=show_ids,
 
4983
                        show_timezone='original')
 
4984
 
 
4985
        status_code = 0
 
4986
        if local_extra and not theirs_only:
 
4987
            message(ngettext("You have %d extra revision:\n",
 
4988
                             "You have %d extra revisions:\n", 
 
4989
                             len(local_extra)) %
 
4990
                len(local_extra))
 
4991
            rev_tag_dict = {}
 
4992
            if local_branch.supports_tags():
 
4993
                rev_tag_dict = local_branch.tags.get_reverse_tag_dict()
 
4994
            for revision in iter_log_revisions(local_extra,
 
4995
                                local_branch.repository,
 
4996
                                verbose,
 
4997
                                rev_tag_dict):
 
4998
                lf.log_revision(revision)
 
4999
            printed_local = True
 
5000
            status_code = 1
 
5001
        else:
 
5002
            printed_local = False
 
5003
 
 
5004
        if remote_extra and not mine_only:
 
5005
            if printed_local is True:
 
5006
                message("\n\n\n")
 
5007
            message(ngettext("You are missing %d revision:\n",
 
5008
                             "You are missing %d revisions:\n",
 
5009
                             len(remote_extra)) %
 
5010
                len(remote_extra))
 
5011
            if remote_branch.supports_tags():
 
5012
                rev_tag_dict = remote_branch.tags.get_reverse_tag_dict()
 
5013
            for revision in iter_log_revisions(remote_extra,
 
5014
                                remote_branch.repository,
 
5015
                                verbose,
 
5016
                                rev_tag_dict):
 
5017
                lf.log_revision(revision)
 
5018
            status_code = 1
 
5019
 
 
5020
        if mine_only and not local_extra:
 
5021
            # We checked local, and found nothing extra
 
5022
            message(gettext('This branch has no new revisions.\n'))
 
5023
        elif theirs_only and not remote_extra:
 
5024
            # We checked remote, and found nothing extra
 
5025
            message(gettext('Other branch has no new revisions.\n'))
 
5026
        elif not (mine_only or theirs_only or local_extra or
 
5027
                  remote_extra):
 
5028
            # We checked both branches, and neither one had extra
 
5029
            # revisions
 
5030
            message(gettext("Branches are up to date.\n"))
 
5031
        self.cleanup_now()
 
5032
        if not status_code and parent is None and other_branch is not None:
 
5033
            self.add_cleanup(local_branch.lock_write().unlock)
 
5034
            # handle race conditions - a parent might be set while we run.
 
5035
            if local_branch.get_parent() is None:
 
5036
                local_branch.set_parent(remote_branch.base)
 
5037
        return status_code
 
5038
 
 
5039
 
 
5040
class cmd_pack(Command):
 
5041
    __doc__ = """Compress the data within a repository.
 
5042
 
 
5043
    This operation compresses the data within a bazaar repository. As
 
5044
    bazaar supports automatic packing of repository, this operation is
 
5045
    normally not required to be done manually.
 
5046
 
 
5047
    During the pack operation, bazaar takes a backup of existing repository
 
5048
    data, i.e. pack files. This backup is eventually removed by bazaar
 
5049
    automatically when it is safe to do so. To save disk space by removing
 
5050
    the backed up pack files, the --clean-obsolete-packs option may be
 
5051
    used.
 
5052
 
 
5053
    Warning: If you use --clean-obsolete-packs and your machine crashes
 
5054
    during or immediately after repacking, you may be left with a state
 
5055
    where the deletion has been written to disk but the new packs have not
 
5056
    been. In this case the repository may be unusable.
 
5057
    """
 
5058
 
 
5059
    _see_also = ['repositories']
 
5060
    takes_args = ['branch_or_repo?']
 
5061
    takes_options = [
 
5062
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
 
5063
        ]
 
5064
 
 
5065
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
 
5066
        dir = controldir.ControlDir.open_containing(branch_or_repo)[0]
 
5067
        try:
 
5068
            branch = dir.open_branch()
 
5069
            repository = branch.repository
 
5070
        except errors.NotBranchError:
 
5071
            repository = dir.open_repository()
 
5072
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
5073
 
 
5074
 
 
5075
class cmd_plugins(Command):
 
5076
    __doc__ = """List the installed plugins.
 
5077
 
 
5078
    This command displays the list of installed plugins including
 
5079
    version of plugin and a short description of each.
 
5080
 
 
5081
    --verbose shows the path where each plugin is located.
 
5082
 
 
5083
    A plugin is an external component for Bazaar that extends the
 
5084
    revision control system, by adding or replacing code in Bazaar.
 
5085
    Plugins can do a variety of things, including overriding commands,
 
5086
    adding new commands, providing additional network transports and
 
5087
    customizing log output.
 
5088
 
 
5089
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
 
5090
    for further information on plugins including where to find them and how to
 
5091
    install them. Instructions are also provided there on how to write new
 
5092
    plugins using the Python programming language.
 
5093
    """
 
5094
    takes_options = ['verbose']
 
5095
 
 
5096
    @display_command
 
5097
    def run(self, verbose=False):
 
5098
        from . import plugin
 
5099
        # Don't give writelines a generator as some codecs don't like that
 
5100
        self.outf.writelines(
 
5101
            list(plugin.describe_plugins(show_paths=verbose)))
 
5102
 
 
5103
 
 
5104
class cmd_testament(Command):
 
5105
    __doc__ = """Show testament (signing-form) of a revision."""
 
5106
    takes_options = [
 
5107
            'revision',
 
5108
            Option('long', help='Produce long-format testament.'),
 
5109
            Option('strict',
 
5110
                   help='Produce a strict-format testament.')]
 
5111
    takes_args = ['branch?']
 
5112
    encoding_type = 'exact'
 
5113
    @display_command
 
5114
    def run(self, branch=u'.', revision=None, long=False, strict=False):
 
5115
        from .testament import Testament, StrictTestament
 
5116
        if strict is True:
 
5117
            testament_class = StrictTestament
 
5118
        else:
 
5119
            testament_class = Testament
 
5120
        if branch == '.':
 
5121
            b = Branch.open_containing(branch)[0]
 
5122
        else:
 
5123
            b = Branch.open(branch)
 
5124
        self.add_cleanup(b.lock_read().unlock)
 
5125
        if revision is None:
 
5126
            rev_id = b.last_revision()
 
5127
        else:
 
5128
            rev_id = revision[0].as_revision_id(b)
 
5129
        t = testament_class.from_revision(b.repository, rev_id)
 
5130
        if long:
 
5131
            self.outf.writelines(t.as_text_lines())
 
5132
        else:
 
5133
            self.outf.write(t.as_short_text())
 
5134
 
 
5135
 
 
5136
class cmd_annotate(Command):
 
5137
    __doc__ = """Show the origin of each line in a file.
 
5138
 
 
5139
    This prints out the given file with an annotation on the left side
 
5140
    indicating which revision, author and date introduced the change.
 
5141
 
 
5142
    If the origin is the same for a run of consecutive lines, it is
 
5143
    shown only at the top, unless the --all option is given.
 
5144
    """
 
5145
    # TODO: annotate directories; showing when each file was last changed
 
5146
    # TODO: if the working copy is modified, show annotations on that
 
5147
    #       with new uncommitted lines marked
 
5148
    aliases = ['ann', 'blame', 'praise']
 
5149
    takes_args = ['filename']
 
5150
    takes_options = [Option('all', help='Show annotations on all lines.'),
 
5151
                     Option('long', help='Show commit date in annotations.'),
 
5152
                     'revision',
 
5153
                     'show-ids',
 
5154
                     'directory',
 
5155
                     ]
 
5156
    encoding_type = 'exact'
 
5157
 
 
5158
    @display_command
 
5159
    def run(self, filename, all=False, long=False, revision=None,
 
5160
            show_ids=False, directory=None):
 
5161
        from .annotate import (
 
5162
            annotate_file_tree,
 
5163
            )
 
5164
        wt, branch, relpath = \
 
5165
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
5166
        if wt is not None:
 
5167
            self.add_cleanup(wt.lock_read().unlock)
 
5168
        else:
 
5169
            self.add_cleanup(branch.lock_read().unlock)
 
5170
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
 
5171
        self.add_cleanup(tree.lock_read().unlock)
 
5172
        if wt is not None and revision is None:
 
5173
            file_id = wt.path2id(relpath)
 
5174
        else:
 
5175
            file_id = tree.path2id(relpath)
 
5176
        if file_id is None:
 
5177
            raise errors.NotVersionedError(filename)
 
5178
        if wt is not None and revision is None:
 
5179
            # If there is a tree and we're not annotating historical
 
5180
            # versions, annotate the working tree's content.
 
5181
            annotate_file_tree(wt, file_id, self.outf, long, all,
 
5182
                show_ids=show_ids)
 
5183
        else:
 
5184
            annotate_file_tree(tree, file_id, self.outf, long, all,
 
5185
                show_ids=show_ids, branch=branch)
 
5186
 
 
5187
 
 
5188
class cmd_re_sign(Command):
 
5189
    __doc__ = """Create a digital signature for an existing revision."""
 
5190
    # TODO be able to replace existing ones.
 
5191
 
 
5192
    hidden = True # is this right ?
 
5193
    takes_args = ['revision_id*']
 
5194
    takes_options = ['directory', 'revision']
 
5195
 
 
5196
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
5197
        if revision_id_list is not None and revision is not None:
 
5198
            raise errors.BzrCommandError(gettext('You can only supply one of revision_id or --revision'))
 
5199
        if revision_id_list is None and revision is None:
 
5200
            raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
 
5201
        b = WorkingTree.open_containing(directory)[0].branch
 
5202
        self.add_cleanup(b.lock_write().unlock)
 
5203
        return self._run(b, revision_id_list, revision)
 
5204
 
 
5205
    def _run(self, b, revision_id_list, revision):
 
5206
        from . import gpg
 
5207
        gpg_strategy = gpg.GPGStrategy(b.get_config_stack())
 
5208
        if revision_id_list is not None:
 
5209
            b.repository.start_write_group()
 
5210
            try:
 
5211
                for revision_id in revision_id_list:
 
5212
                    revision_id = cache_utf8.encode(revision_id)
 
5213
                    b.repository.sign_revision(revision_id, gpg_strategy)
 
5214
            except:
 
5215
                b.repository.abort_write_group()
 
5216
                raise
 
5217
            else:
 
5218
                b.repository.commit_write_group()
 
5219
        elif revision is not None:
 
5220
            if len(revision) == 1:
 
5221
                revno, rev_id = revision[0].in_history(b)
 
5222
                b.repository.start_write_group()
 
5223
                try:
 
5224
                    b.repository.sign_revision(rev_id, gpg_strategy)
 
5225
                except:
 
5226
                    b.repository.abort_write_group()
 
5227
                    raise
 
5228
                else:
 
5229
                    b.repository.commit_write_group()
 
5230
            elif len(revision) == 2:
 
5231
                # are they both on rh- if so we can walk between them
 
5232
                # might be nice to have a range helper for arbitrary
 
5233
                # revision paths. hmm.
 
5234
                from_revno, from_revid = revision[0].in_history(b)
 
5235
                to_revno, to_revid = revision[1].in_history(b)
 
5236
                if to_revid is None:
 
5237
                    to_revno = b.revno()
 
5238
                if from_revno is None or to_revno is None:
 
5239
                    raise errors.BzrCommandError(gettext('Cannot sign a range of non-revision-history revisions'))
 
5240
                b.repository.start_write_group()
 
5241
                try:
 
5242
                    for revno in range(from_revno, to_revno + 1):
 
5243
                        b.repository.sign_revision(b.get_rev_id(revno),
 
5244
                                                   gpg_strategy)
 
5245
                except:
 
5246
                    b.repository.abort_write_group()
 
5247
                    raise
 
5248
                else:
 
5249
                    b.repository.commit_write_group()
 
5250
            else:
 
5251
                raise errors.BzrCommandError(gettext('Please supply either one revision, or a range.'))
 
5252
 
 
5253
 
 
5254
class cmd_bind(Command):
 
5255
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
 
5256
    If no branch is supplied, rebind to the last bound location.
 
5257
 
 
5258
    Once converted into a checkout, commits must succeed on the master branch
 
5259
    before they will be applied to the local branch.
 
5260
 
 
5261
    Bound branches use the nickname of its master branch unless it is set
 
5262
    locally, in which case binding will update the local nickname to be
 
5263
    that of the master.
 
5264
    """
 
5265
 
 
5266
    _see_also = ['checkouts', 'unbind']
 
5267
    takes_args = ['location?']
 
5268
    takes_options = ['directory']
 
5269
 
 
5270
    def run(self, location=None, directory=u'.'):
 
5271
        b, relpath = Branch.open_containing(directory)
 
5272
        if location is None:
 
5273
            try:
 
5274
                location = b.get_old_bound_location()
 
5275
            except errors.UpgradeRequired:
 
5276
                raise errors.BzrCommandError(gettext('No location supplied.  '
 
5277
                    'This format does not remember old locations.'))
 
5278
            else:
 
5279
                if location is None:
 
5280
                    if b.get_bound_location() is not None:
 
5281
                        raise errors.BzrCommandError(
 
5282
                            gettext('Branch is already bound'))
 
5283
                    else:
 
5284
                        raise errors.BzrCommandError(
 
5285
                            gettext('No location supplied'
 
5286
                                    ' and no previous location known'))
 
5287
        b_other = Branch.open(location)
 
5288
        try:
 
5289
            b.bind(b_other)
 
5290
        except errors.DivergedBranches:
 
5291
            raise errors.BzrCommandError(gettext('These branches have diverged.'
 
5292
                                         ' Try merging, and then bind again.'))
 
5293
        if b.get_config().has_explicit_nickname():
 
5294
            b.nick = b_other.nick
 
5295
 
 
5296
 
 
5297
class cmd_unbind(Command):
 
5298
    __doc__ = """Convert the current checkout into a regular branch.
 
5299
 
 
5300
    After unbinding, the local branch is considered independent and subsequent
 
5301
    commits will be local only.
 
5302
    """
 
5303
 
 
5304
    _see_also = ['checkouts', 'bind']
 
5305
    takes_args = []
 
5306
    takes_options = ['directory']
 
5307
 
 
5308
    def run(self, directory=u'.'):
 
5309
        b, relpath = Branch.open_containing(directory)
 
5310
        if not b.unbind():
 
5311
            raise errors.BzrCommandError(gettext('Local branch is not bound'))
 
5312
 
 
5313
 
 
5314
class cmd_uncommit(Command):
 
5315
    __doc__ = """Remove the last committed revision.
 
5316
 
 
5317
    --verbose will print out what is being removed.
 
5318
    --dry-run will go through all the motions, but not actually
 
5319
    remove anything.
 
5320
 
 
5321
    If --revision is specified, uncommit revisions to leave the branch at the
 
5322
    specified revision.  For example, "brz uncommit -r 15" will leave the
 
5323
    branch at revision 15.
 
5324
 
 
5325
    Uncommit leaves the working tree ready for a new commit.  The only change
 
5326
    it may make is to restore any pending merges that were present before
 
5327
    the commit.
 
5328
    """
 
5329
 
 
5330
    # TODO: jam 20060108 Add an option to allow uncommit to remove
 
5331
    # unreferenced information in 'branch-as-repository' branches.
 
5332
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
 
5333
    # information in shared branches as well.
 
5334
    _see_also = ['commit']
 
5335
    takes_options = ['verbose', 'revision',
 
5336
                    Option('dry-run', help='Don\'t actually make changes.'),
 
5337
                    Option('force', help='Say yes to all questions.'),
 
5338
                    Option('keep-tags',
 
5339
                           help='Keep tags that point to removed revisions.'),
 
5340
                    Option('local',
 
5341
                           help="Only remove the commits from the local branch"
 
5342
                                " when in a checkout."
 
5343
                           ),
 
5344
                    ]
 
5345
    takes_args = ['location?']
 
5346
    aliases = []
 
5347
    encoding_type = 'replace'
 
5348
 
 
5349
    def run(self, location=None, dry_run=False, verbose=False,
 
5350
            revision=None, force=False, local=False, keep_tags=False):
 
5351
        if location is None:
 
5352
            location = u'.'
 
5353
        control, relpath = controldir.ControlDir.open_containing(location)
 
5354
        try:
 
5355
            tree = control.open_workingtree()
 
5356
            b = tree.branch
 
5357
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
5358
            tree = None
 
5359
            b = control.open_branch()
 
5360
 
 
5361
        if tree is not None:
 
5362
            self.add_cleanup(tree.lock_write().unlock)
 
5363
        else:
 
5364
            self.add_cleanup(b.lock_write().unlock)
 
5365
        return self._run(b, tree, dry_run, verbose, revision, force,
 
5366
                         local, keep_tags)
 
5367
 
 
5368
    def _run(self, b, tree, dry_run, verbose, revision, force, local,
 
5369
             keep_tags):
 
5370
        from .log import log_formatter, show_log
 
5371
        from .uncommit import uncommit
 
5372
 
 
5373
        last_revno, last_rev_id = b.last_revision_info()
 
5374
 
 
5375
        rev_id = None
 
5376
        if revision is None:
 
5377
            revno = last_revno
 
5378
            rev_id = last_rev_id
 
5379
        else:
 
5380
            # 'brz uncommit -r 10' actually means uncommit
 
5381
            # so that the final tree is at revno 10.
 
5382
            # but breezy.uncommit.uncommit() actually uncommits
 
5383
            # the revisions that are supplied.
 
5384
            # So we need to offset it by one
 
5385
            revno = revision[0].in_history(b).revno + 1
 
5386
            if revno <= last_revno:
 
5387
                rev_id = b.get_rev_id(revno)
 
5388
 
 
5389
        if rev_id is None or _mod_revision.is_null(rev_id):
 
5390
            self.outf.write(gettext('No revisions to uncommit.\n'))
 
5391
            return 1
 
5392
 
 
5393
        lf = log_formatter('short',
 
5394
                           to_file=self.outf,
 
5395
                           show_timezone='original')
 
5396
 
 
5397
        show_log(b,
 
5398
                 lf,
 
5399
                 verbose=False,
 
5400
                 direction='forward',
 
5401
                 start_revision=revno,
 
5402
                 end_revision=last_revno)
 
5403
 
 
5404
        if dry_run:
 
5405
            self.outf.write(gettext('Dry-run, pretending to remove'
 
5406
                            ' the above revisions.\n'))
 
5407
        else:
 
5408
            self.outf.write(gettext('The above revision(s) will be removed.\n'))
 
5409
 
 
5410
        if not force:
 
5411
            if not ui.ui_factory.confirm_action(
 
5412
                    gettext(u'Uncommit these revisions'),
 
5413
                    'breezy.builtins.uncommit',
 
5414
                    {}):
 
5415
                self.outf.write(gettext('Canceled\n'))
 
5416
                return 0
 
5417
 
 
5418
        mutter('Uncommitting from {%s} to {%s}',
 
5419
               last_rev_id, rev_id)
 
5420
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
 
5421
                 revno=revno, local=local, keep_tags=keep_tags)
 
5422
        self.outf.write(gettext('You can restore the old tip by running:\n'
 
5423
             '  brz pull . -r revid:%s\n') % last_rev_id)
 
5424
 
 
5425
 
 
5426
class cmd_break_lock(Command):
 
5427
    __doc__ = """Break a dead lock.
 
5428
 
 
5429
    This command breaks a lock on a repository, branch, working directory or
 
5430
    config file.
 
5431
 
 
5432
    CAUTION: Locks should only be broken when you are sure that the process
 
5433
    holding the lock has been stopped.
 
5434
 
 
5435
    You can get information on what locks are open via the 'brz info
 
5436
    [location]' command.
 
5437
 
 
5438
    :Examples:
 
5439
        brz break-lock
 
5440
        brz break-lock brz+ssh://example.com/brz/foo
 
5441
        brz break-lock --conf ~/.bazaar
 
5442
    """
 
5443
 
 
5444
    takes_args = ['location?']
 
5445
    takes_options = [
 
5446
        Option('config',
 
5447
               help='LOCATION is the directory where the config lock is.'),
 
5448
        Option('force',
 
5449
            help='Do not ask for confirmation before breaking the lock.'),
 
5450
        ]
 
5451
 
 
5452
    def run(self, location=None, config=False, force=False):
 
5453
        if location is None:
 
5454
            location = u'.'
 
5455
        if force:
 
5456
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
 
5457
                None,
 
5458
                {'breezy.lockdir.break': True})
 
5459
        if config:
 
5460
            conf = _mod_config.LockableConfig(file_name=location)
 
5461
            conf.break_lock()
 
5462
        else:
 
5463
            control, relpath = controldir.ControlDir.open_containing(location)
 
5464
            try:
 
5465
                control.break_lock()
 
5466
            except NotImplementedError:
 
5467
                pass
 
5468
 
 
5469
 
 
5470
class cmd_wait_until_signalled(Command):
 
5471
    __doc__ = """Test helper for test_start_and_stop_brz_subprocess_send_signal.
 
5472
 
 
5473
    This just prints a line to signal when it is ready, then blocks on stdin.
 
5474
    """
 
5475
 
 
5476
    hidden = True
 
5477
 
 
5478
    def run(self):
 
5479
        sys.stdout.write("running\n")
 
5480
        sys.stdout.flush()
 
5481
        sys.stdin.readline()
 
5482
 
 
5483
 
 
5484
class cmd_serve(Command):
 
5485
    __doc__ = """Run the brz server."""
 
5486
 
 
5487
    aliases = ['server']
 
5488
 
 
5489
    takes_options = [
 
5490
        Option('inet',
 
5491
               help='Serve on stdin/out for use from inetd or sshd.'),
 
5492
        RegistryOption('protocol',
 
5493
               help="Protocol to serve.",
 
5494
               lazy_registry=('breezy.transport', 'transport_server_registry'),
 
5495
               value_switches=True),
 
5496
        Option('listen',
 
5497
               help='Listen for connections on nominated address.', type=str),
 
5498
        Option('port',
 
5499
               help='Listen for connections on nominated port.  Passing 0 as '
 
5500
                    'the port number will result in a dynamically allocated '
 
5501
                    'port.  The default port depends on the protocol.',
 
5502
               type=int),
 
5503
        custom_help('directory',
 
5504
               help='Serve contents of this directory.'),
 
5505
        Option('allow-writes',
 
5506
               help='By default the server is a readonly server.  Supplying '
 
5507
                    '--allow-writes enables write access to the contents of '
 
5508
                    'the served directory and below.  Note that ``brz serve`` '
 
5509
                    'does not perform authentication, so unless some form of '
 
5510
                    'external authentication is arranged supplying this '
 
5511
                    'option leads to global uncontrolled write access to your '
 
5512
                    'file system.'
 
5513
                ),
 
5514
        Option('client-timeout', type=float,
 
5515
               help='Override the default idle client timeout (5min).'),
 
5516
        ]
 
5517
 
 
5518
    def run(self, listen=None, port=None, inet=False, directory=None,
 
5519
            allow_writes=False, protocol=None, client_timeout=None):
 
5520
        from . import transport
 
5521
        if directory is None:
 
5522
            directory = osutils.getcwd()
 
5523
        if protocol is None:
 
5524
            protocol = transport.transport_server_registry.get()
 
5525
        url = transport.location_to_url(directory)
 
5526
        if not allow_writes:
 
5527
            url = 'readonly+' + url
 
5528
        t = transport.get_transport_from_url(url)
 
5529
        protocol(t, listen, port, inet, client_timeout)
 
5530
 
 
5531
 
 
5532
class cmd_join(Command):
 
5533
    __doc__ = """Combine a tree into its containing tree.
 
5534
 
 
5535
    This command requires the target tree to be in a rich-root format.
 
5536
 
 
5537
    The TREE argument should be an independent tree, inside another tree, but
 
5538
    not part of it.  (Such trees can be produced by "brz split", but also by
 
5539
    running "brz branch" with the target inside a tree.)
 
5540
 
 
5541
    The result is a combined tree, with the subtree no longer an independent
 
5542
    part.  This is marked as a merge of the subtree into the containing tree,
 
5543
    and all history is preserved.
 
5544
    """
 
5545
 
 
5546
    _see_also = ['split']
 
5547
    takes_args = ['tree']
 
5548
    takes_options = [
 
5549
            Option('reference', help='Join by reference.', hidden=True),
 
5550
            ]
 
5551
 
 
5552
    def run(self, tree, reference=False):
 
5553
        sub_tree = WorkingTree.open(tree)
 
5554
        parent_dir = osutils.dirname(sub_tree.basedir)
 
5555
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
 
5556
        repo = containing_tree.branch.repository
 
5557
        if not repo.supports_rich_root():
 
5558
            raise errors.BzrCommandError(gettext(
 
5559
                "Can't join trees because %s doesn't support rich root data.\n"
 
5560
                "You can use brz upgrade on the repository.")
 
5561
                % (repo,))
 
5562
        if reference:
 
5563
            try:
 
5564
                containing_tree.add_reference(sub_tree)
 
5565
            except errors.BadReferenceTarget as e:
 
5566
                # XXX: Would be better to just raise a nicely printable
 
5567
                # exception from the real origin.  Also below.  mbp 20070306
 
5568
                raise errors.BzrCommandError(
 
5569
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
5570
        else:
 
5571
            try:
 
5572
                containing_tree.subsume(sub_tree)
 
5573
            except errors.BadSubsumeSource as e:
 
5574
                raise errors.BzrCommandError(
 
5575
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
5576
 
 
5577
 
 
5578
class cmd_split(Command):
 
5579
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
5580
 
 
5581
    This command will produce a target tree in a format that supports
 
5582
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
 
5583
    converted into earlier formats like 'dirstate-tags'.
 
5584
 
 
5585
    The TREE argument should be a subdirectory of a working tree.  That
 
5586
    subdirectory will be converted into an independent tree, with its own
 
5587
    branch.  Commits in the top-level tree will not apply to the new subtree.
 
5588
    """
 
5589
 
 
5590
    _see_also = ['join']
 
5591
    takes_args = ['tree']
 
5592
 
 
5593
    def run(self, tree):
 
5594
        containing_tree, subdir = WorkingTree.open_containing(tree)
 
5595
        sub_id = containing_tree.path2id(subdir)
 
5596
        if sub_id is None:
 
5597
            raise errors.NotVersionedError(subdir)
 
5598
        try:
 
5599
            containing_tree.extract(sub_id)
 
5600
        except errors.RootNotRich:
 
5601
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
 
5602
 
 
5603
 
 
5604
class cmd_merge_directive(Command):
 
5605
    __doc__ = """Generate a merge directive for auto-merge tools.
 
5606
 
 
5607
    A directive requests a merge to be performed, and also provides all the
 
5608
    information necessary to do so.  This means it must either include a
 
5609
    revision bundle, or the location of a branch containing the desired
 
5610
    revision.
 
5611
 
 
5612
    A submit branch (the location to merge into) must be supplied the first
 
5613
    time the command is issued.  After it has been supplied once, it will
 
5614
    be remembered as the default.
 
5615
 
 
5616
    A public branch is optional if a revision bundle is supplied, but required
 
5617
    if --diff or --plain is specified.  It will be remembered as the default
 
5618
    after the first use.
 
5619
    """
 
5620
 
 
5621
    takes_args = ['submit_branch?', 'public_branch?']
 
5622
 
 
5623
    hidden = True
 
5624
 
 
5625
    _see_also = ['send']
 
5626
 
 
5627
    takes_options = [
 
5628
        'directory',
 
5629
        RegistryOption.from_kwargs('patch-type',
 
5630
            'The type of patch to include in the directive.',
 
5631
            title='Patch type',
 
5632
            value_switches=True,
 
5633
            enum_switch=False,
 
5634
            bundle='Bazaar revision bundle (default).',
 
5635
            diff='Normal unified diff.',
 
5636
            plain='No patch, just directive.'),
 
5637
        Option('sign', help='GPG-sign the directive.'), 'revision',
 
5638
        Option('mail-to', type=str,
 
5639
            help='Instead of printing the directive, email to this address.'),
 
5640
        Option('message', type=str, short_name='m',
 
5641
            help='Message to use when committing this merge.')
 
5642
        ]
 
5643
 
 
5644
    encoding_type = 'exact'
 
5645
 
 
5646
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
 
5647
            sign=False, revision=None, mail_to=None, message=None,
 
5648
            directory=u'.'):
 
5649
        from .revision import ensure_null, NULL_REVISION
 
5650
        include_patch, include_bundle = {
 
5651
            'plain': (False, False),
 
5652
            'diff': (True, False),
 
5653
            'bundle': (True, True),
 
5654
            }[patch_type]
 
5655
        branch = Branch.open(directory)
 
5656
        stored_submit_branch = branch.get_submit_branch()
 
5657
        if submit_branch is None:
 
5658
            submit_branch = stored_submit_branch
 
5659
        else:
 
5660
            if stored_submit_branch is None:
 
5661
                branch.set_submit_branch(submit_branch)
 
5662
        if submit_branch is None:
 
5663
            submit_branch = branch.get_parent()
 
5664
        if submit_branch is None:
 
5665
            raise errors.BzrCommandError(gettext('No submit branch specified or known'))
 
5666
 
 
5667
        stored_public_branch = branch.get_public_branch()
 
5668
        if public_branch is None:
 
5669
            public_branch = stored_public_branch
 
5670
        elif stored_public_branch is None:
 
5671
            # FIXME: Should be done only if we succeed ? -- vila 2012-01-03
 
5672
            branch.set_public_branch(public_branch)
 
5673
        if not include_bundle and public_branch is None:
 
5674
            raise errors.BzrCommandError(gettext('No public branch specified or'
 
5675
                                         ' known'))
 
5676
        base_revision_id = None
 
5677
        if revision is not None:
 
5678
            if len(revision) > 2:
 
5679
                raise errors.BzrCommandError(gettext('brz merge-directive takes '
 
5680
                    'at most two one revision identifiers'))
 
5681
            revision_id = revision[-1].as_revision_id(branch)
 
5682
            if len(revision) == 2:
 
5683
                base_revision_id = revision[0].as_revision_id(branch)
 
5684
        else:
 
5685
            revision_id = branch.last_revision()
 
5686
        revision_id = ensure_null(revision_id)
 
5687
        if revision_id == NULL_REVISION:
 
5688
            raise errors.BzrCommandError(gettext('No revisions to bundle.'))
 
5689
        directive = merge_directive.MergeDirective2.from_objects(
 
5690
            branch.repository, revision_id, time.time(),
 
5691
            osutils.local_time_offset(), submit_branch,
 
5692
            public_branch=public_branch, include_patch=include_patch,
 
5693
            include_bundle=include_bundle, message=message,
 
5694
            base_revision_id=base_revision_id)
 
5695
        if mail_to is None:
 
5696
            if sign:
 
5697
                self.outf.write(directive.to_signed(branch))
 
5698
            else:
 
5699
                self.outf.writelines(directive.to_lines())
 
5700
        else:
 
5701
            message = directive.to_email(mail_to, branch, sign)
 
5702
            s = SMTPConnection(branch.get_config_stack())
 
5703
            s.send_email(message)
 
5704
 
 
5705
 
 
5706
class cmd_send(Command):
 
5707
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
5708
 
 
5709
    A merge directive provides many things needed for requesting merges:
 
5710
 
 
5711
    * A machine-readable description of the merge to perform
 
5712
 
 
5713
    * An optional patch that is a preview of the changes requested
 
5714
 
 
5715
    * An optional bundle of revision data, so that the changes can be applied
 
5716
      directly from the merge directive, without retrieving data from a
 
5717
      branch.
 
5718
 
 
5719
    `brz send` creates a compact data set that, when applied using brz
 
5720
    merge, has the same effect as merging from the source branch.  
 
5721
    
 
5722
    By default the merge directive is self-contained and can be applied to any
 
5723
    branch containing submit_branch in its ancestory without needing access to
 
5724
    the source branch.
 
5725
    
 
5726
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
 
5727
    revisions, but only a structured request to merge from the
 
5728
    public_location.  In that case the public_branch is needed and it must be
 
5729
    up-to-date and accessible to the recipient.  The public_branch is always
 
5730
    included if known, so that people can check it later.
 
5731
 
 
5732
    The submit branch defaults to the parent of the source branch, but can be
 
5733
    overridden.  Both submit branch and public branch will be remembered in
 
5734
    branch.conf the first time they are used for a particular branch.  The
 
5735
    source branch defaults to that containing the working directory, but can
 
5736
    be changed using --from.
 
5737
 
 
5738
    Both the submit branch and the public branch follow the usual behavior with
 
5739
    respect to --remember: If there is no default location set, the first send
 
5740
    will set it (use --no-remember to avoid setting it). After that, you can
 
5741
    omit the location to use the default.  To change the default, use
 
5742
    --remember. The value will only be saved if the location can be accessed.
 
5743
 
 
5744
    In order to calculate those changes, brz must analyse the submit branch.
 
5745
    Therefore it is most efficient for the submit branch to be a local mirror.
 
5746
    If a public location is known for the submit_branch, that location is used
 
5747
    in the merge directive.
 
5748
 
 
5749
    The default behaviour is to send the merge directive by mail, unless -o is
 
5750
    given, in which case it is sent to a file.
 
5751
 
 
5752
    Mail is sent using your preferred mail program.  This should be transparent
 
5753
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
5754
    If the preferred client can't be found (or used), your editor will be used.
 
5755
 
 
5756
    To use a specific mail program, set the mail_client configuration option.
 
5757
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
 
5758
    specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
 
5759
    Mail.app), "mutt", and "thunderbird"; generic options are "default",
 
5760
    "editor", "emacsclient", "mapi", and "xdg-email".  Plugins may also add
 
5761
    supported clients.
 
5762
 
 
5763
    If mail is being sent, a to address is required.  This can be supplied
 
5764
    either on the commandline, by setting the submit_to configuration
 
5765
    option in the branch itself or the child_submit_to configuration option
 
5766
    in the submit branch.
 
5767
 
 
5768
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
5769
    merge directive format 2.  It is significantly faster and smaller than
 
5770
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
5771
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
5772
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
5773
 
 
5774
    The merge directives created by brz send may be applied using brz merge or
 
5775
    brz pull by specifying a file containing a merge directive as the location.
 
5776
 
 
5777
    brz send makes extensive use of public locations to map local locations into
 
5778
    URLs that can be used by other people.  See `brz help configuration` to
 
5779
    set them, and use `brz info` to display them.
 
5780
    """
 
5781
 
 
5782
    encoding_type = 'exact'
 
5783
 
 
5784
    _see_also = ['merge', 'pull']
 
5785
 
 
5786
    takes_args = ['submit_branch?', 'public_branch?']
 
5787
 
 
5788
    takes_options = [
 
5789
        Option('no-bundle',
 
5790
               help='Do not include a bundle in the merge directive.'),
 
5791
        Option('no-patch', help='Do not include a preview patch in the merge'
 
5792
               ' directive.'),
 
5793
        Option('remember',
 
5794
               help='Remember submit and public branch.'),
 
5795
        Option('from',
 
5796
               help='Branch to generate the submission from, '
 
5797
               'rather than the one containing the working directory.',
 
5798
               short_name='f',
 
5799
               type=text_type),
 
5800
        Option('output', short_name='o',
 
5801
               help='Write merge directive to this file or directory; '
 
5802
                    'use - for stdout.',
 
5803
               type=text_type),
 
5804
        Option('strict',
 
5805
               help='Refuse to send if there are uncommitted changes in'
 
5806
               ' the working tree, --no-strict disables the check.'),
 
5807
        Option('mail-to', help='Mail the request to this address.',
 
5808
               type=text_type),
 
5809
        'revision',
 
5810
        'message',
 
5811
        Option('body', help='Body for the email.', type=text_type),
 
5812
        RegistryOption('format',
 
5813
                       help='Use the specified output format.',
 
5814
                       lazy_registry=('breezy.send', 'format_registry')),
 
5815
        ]
 
5816
 
 
5817
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
5818
            no_patch=False, revision=None, remember=None, output=None,
 
5819
            format=None, mail_to=None, message=None, body=None,
 
5820
            strict=None, **kwargs):
 
5821
        from .send import send
 
5822
        return send(submit_branch, revision, public_branch, remember,
 
5823
                    format, no_bundle, no_patch, output,
 
5824
                    kwargs.get('from', '.'), mail_to, message, body,
 
5825
                    self.outf,
 
5826
                    strict=strict)
 
5827
 
 
5828
 
 
5829
class cmd_bundle_revisions(cmd_send):
 
5830
    __doc__ = """Create a merge-directive for submitting changes.
 
5831
 
 
5832
    A merge directive provides many things needed for requesting merges:
 
5833
 
 
5834
    * A machine-readable description of the merge to perform
 
5835
 
 
5836
    * An optional patch that is a preview of the changes requested
 
5837
 
 
5838
    * An optional bundle of revision data, so that the changes can be applied
 
5839
      directly from the merge directive, without retrieving data from a
 
5840
      branch.
 
5841
 
 
5842
    If --no-bundle is specified, then public_branch is needed (and must be
 
5843
    up-to-date), so that the receiver can perform the merge using the
 
5844
    public_branch.  The public_branch is always included if known, so that
 
5845
    people can check it later.
 
5846
 
 
5847
    The submit branch defaults to the parent, but can be overridden.  Both
 
5848
    submit branch and public branch will be remembered if supplied.
 
5849
 
 
5850
    If a public_branch is known for the submit_branch, that public submit
 
5851
    branch is used in the merge instructions.  This means that a local mirror
 
5852
    can be used as your actual submit branch, once you have set public_branch
 
5853
    for that mirror.
 
5854
 
 
5855
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
5856
    merge directive format 2.  It is significantly faster and smaller than
 
5857
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
5858
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
5859
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
5860
    """
 
5861
 
 
5862
    takes_options = [
 
5863
        Option('no-bundle',
 
5864
               help='Do not include a bundle in the merge directive.'),
 
5865
        Option('no-patch', help='Do not include a preview patch in the merge'
 
5866
               ' directive.'),
 
5867
        Option('remember',
 
5868
               help='Remember submit and public branch.'),
 
5869
        Option('from',
 
5870
               help='Branch to generate the submission from, '
 
5871
               'rather than the one containing the working directory.',
 
5872
               short_name='f',
 
5873
               type=text_type),
 
5874
        Option('output', short_name='o', help='Write directive to this file.',
 
5875
               type=text_type),
 
5876
        Option('strict',
 
5877
               help='Refuse to bundle revisions if there are uncommitted'
 
5878
               ' changes in the working tree, --no-strict disables the check.'),
 
5879
        'revision',
 
5880
        RegistryOption('format',
 
5881
                       help='Use the specified output format.',
 
5882
                       lazy_registry=('breezy.send', 'format_registry')),
 
5883
        ]
 
5884
    aliases = ['bundle']
 
5885
 
 
5886
    _see_also = ['send', 'merge']
 
5887
 
 
5888
    hidden = True
 
5889
 
 
5890
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
5891
            no_patch=False, revision=None, remember=False, output=None,
 
5892
            format=None, strict=None, **kwargs):
 
5893
        if output is None:
 
5894
            output = '-'
 
5895
        from .send import send
 
5896
        return send(submit_branch, revision, public_branch, remember,
 
5897
                         format, no_bundle, no_patch, output,
 
5898
                         kwargs.get('from', '.'), None, None, None,
 
5899
                         self.outf, strict=strict)
 
5900
 
 
5901
 
 
5902
class cmd_tag(Command):
 
5903
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5904
 
 
5905
    Tags give human-meaningful names to revisions.  Commands that take a -r
 
5906
    (--revision) option can be given -rtag:X, where X is any previously
 
5907
    created tag.
 
5908
 
 
5909
    Tags are stored in the branch.  Tags are copied from one branch to another
 
5910
    along when you branch, push, pull or merge.
 
5911
 
 
5912
    It is an error to give a tag name that already exists unless you pass
 
5913
    --force, in which case the tag is moved to point to the new revision.
 
5914
 
 
5915
    To rename a tag (change the name but keep it on the same revsion), run ``brz
 
5916
    tag new-name -r tag:old-name`` and then ``brz tag --delete oldname``.
 
5917
 
 
5918
    If no tag name is specified it will be determined through the 
 
5919
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
 
5920
    upstream releases by reading configure.ac. See ``brz help hooks`` for
 
5921
    details.
 
5922
    """
 
5923
 
 
5924
    _see_also = ['commit', 'tags']
 
5925
    takes_args = ['tag_name?']
 
5926
    takes_options = [
 
5927
        Option('delete',
 
5928
            help='Delete this tag rather than placing it.',
 
5929
            ),
 
5930
        custom_help('directory',
 
5931
            help='Branch in which to place the tag.'),
 
5932
        Option('force',
 
5933
            help='Replace existing tags.',
 
5934
            ),
 
5935
        'revision',
 
5936
        ]
 
5937
 
 
5938
    def run(self, tag_name=None,
 
5939
            delete=None,
 
5940
            directory='.',
 
5941
            force=None,
 
5942
            revision=None,
 
5943
            ):
 
5944
        branch, relpath = Branch.open_containing(directory)
 
5945
        self.add_cleanup(branch.lock_write().unlock)
 
5946
        if delete:
 
5947
            if tag_name is None:
 
5948
                raise errors.BzrCommandError(gettext("No tag specified to delete."))
 
5949
            branch.tags.delete_tag(tag_name)
 
5950
            note(gettext('Deleted tag %s.') % tag_name)
 
5951
        else:
 
5952
            if revision:
 
5953
                if len(revision) != 1:
 
5954
                    raise errors.BzrCommandError(gettext(
 
5955
                        "Tags can only be placed on a single revision, "
 
5956
                        "not on a range"))
 
5957
                revision_id = revision[0].as_revision_id(branch)
 
5958
            else:
 
5959
                revision_id = branch.last_revision()
 
5960
            if tag_name is None:
 
5961
                tag_name = branch.automatic_tag_name(revision_id)
 
5962
                if tag_name is None:
 
5963
                    raise errors.BzrCommandError(gettext(
 
5964
                        "Please specify a tag name."))
 
5965
            try:
 
5966
                existing_target = branch.tags.lookup_tag(tag_name)
 
5967
            except errors.NoSuchTag:
 
5968
                existing_target = None
 
5969
            if not force and existing_target not in (None, revision_id):
 
5970
                raise errors.TagAlreadyExists(tag_name)
 
5971
            if existing_target == revision_id:
 
5972
                note(gettext('Tag %s already exists for that revision.') % tag_name)
 
5973
            else:
 
5974
                branch.tags.set_tag(tag_name, revision_id)
 
5975
                if existing_target is None:
 
5976
                    note(gettext('Created tag %s.') % tag_name)
 
5977
                else:
 
5978
                    note(gettext('Updated tag %s.') % tag_name)
 
5979
 
 
5980
 
 
5981
class cmd_tags(Command):
 
5982
    __doc__ = """List tags.
 
5983
 
 
5984
    This command shows a table of tag names and the revisions they reference.
 
5985
    """
 
5986
 
 
5987
    _see_also = ['tag']
 
5988
    takes_options = [
 
5989
        custom_help('directory',
 
5990
            help='Branch whose tags should be displayed.'),
 
5991
        RegistryOption('sort',
 
5992
            'Sort tags by different criteria.', title='Sorting',
 
5993
            lazy_registry=('breezy.tag', 'tag_sort_methods')
 
5994
            ),
 
5995
        'show-ids',
 
5996
        'revision',
 
5997
    ]
 
5998
 
 
5999
    @display_command
 
6000
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
 
6001
        from .tag import tag_sort_methods
 
6002
        branch, relpath = Branch.open_containing(directory)
 
6003
 
 
6004
        tags = list(viewitems(branch.tags.get_tag_dict()))
 
6005
        if not tags:
 
6006
            return
 
6007
 
 
6008
        self.add_cleanup(branch.lock_read().unlock)
 
6009
        if revision:
 
6010
            # Restrict to the specified range
 
6011
            tags = self._tags_for_range(branch, revision)
 
6012
        if sort is None:
 
6013
            sort = tag_sort_methods.get()
 
6014
        sort(branch, tags)
 
6015
        if not show_ids:
 
6016
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
6017
            for index, (tag, revid) in enumerate(tags):
 
6018
                try:
 
6019
                    revno = branch.revision_id_to_dotted_revno(revid)
 
6020
                    if isinstance(revno, tuple):
 
6021
                        revno = '.'.join(map(str, revno))
 
6022
                except (errors.NoSuchRevision,
 
6023
                        errors.GhostRevisionsHaveNoRevno,
 
6024
                        errors.UnsupportedOperation):
 
6025
                    # Bad tag data/merges can lead to tagged revisions
 
6026
                    # which are not in this branch. Fail gracefully ...
 
6027
                    revno = '?'
 
6028
                tags[index] = (tag, revno)
 
6029
        self.cleanup_now()
 
6030
        for tag, revspec in tags:
 
6031
            self.outf.write('%-20s %s\n' % (tag, revspec))
 
6032
 
 
6033
    def _tags_for_range(self, branch, revision):
 
6034
        range_valid = True
 
6035
        rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
6036
        revid1, revid2 = rev1.rev_id, rev2.rev_id
 
6037
        # _get_revision_range will always set revid2 if it's not specified.
 
6038
        # If revid1 is None, it means we want to start from the branch
 
6039
        # origin which is always a valid ancestor. If revid1 == revid2, the
 
6040
        # ancestry check is useless.
 
6041
        if revid1 and revid1 != revid2:
 
6042
            # FIXME: We really want to use the same graph than
 
6043
            # branch.iter_merge_sorted_revisions below, but this is not
 
6044
            # easily available -- vila 2011-09-23
 
6045
            if branch.repository.get_graph().is_ancestor(revid2, revid1):
 
6046
                # We don't want to output anything in this case...
 
6047
                return []
 
6048
        # only show revisions between revid1 and revid2 (inclusive)
 
6049
        tagged_revids = branch.tags.get_reverse_tag_dict()
 
6050
        found = []
 
6051
        for r in branch.iter_merge_sorted_revisions(
 
6052
            start_revision_id=revid2, stop_revision_id=revid1,
 
6053
            stop_rule='include'):
 
6054
            revid_tags = tagged_revids.get(r[0], None)
 
6055
            if revid_tags:
 
6056
                found.extend([(tag, r[0]) for tag in revid_tags])
 
6057
        return found
 
6058
 
 
6059
 
 
6060
class cmd_reconfigure(Command):
 
6061
    __doc__ = """Reconfigure the type of a brz directory.
 
6062
 
 
6063
    A target configuration must be specified.
 
6064
 
 
6065
    For checkouts, the bind-to location will be auto-detected if not specified.
 
6066
    The order of preference is
 
6067
    1. For a lightweight checkout, the current bound location.
 
6068
    2. For branches that used to be checkouts, the previously-bound location.
 
6069
    3. The push location.
 
6070
    4. The parent location.
 
6071
    If none of these is available, --bind-to must be specified.
 
6072
    """
 
6073
 
 
6074
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
 
6075
    takes_args = ['location?']
 
6076
    takes_options = [
 
6077
        RegistryOption.from_kwargs(
 
6078
            'tree_type',
 
6079
            title='Tree type',
 
6080
            help='The relation between branch and tree.',
 
6081
            value_switches=True, enum_switch=False,
 
6082
            branch='Reconfigure to be an unbound branch with no working tree.',
 
6083
            tree='Reconfigure to be an unbound branch with a working tree.',
 
6084
            checkout='Reconfigure to be a bound branch with a working tree.',
 
6085
            lightweight_checkout='Reconfigure to be a lightweight'
 
6086
                ' checkout (with no local history).',
 
6087
            ),
 
6088
        RegistryOption.from_kwargs(
 
6089
            'repository_type',
 
6090
            title='Repository type',
 
6091
            help='Location fo the repository.',
 
6092
            value_switches=True, enum_switch=False,
 
6093
            standalone='Reconfigure to be a standalone branch '
 
6094
                '(i.e. stop using shared repository).',
 
6095
            use_shared='Reconfigure to use a shared repository.',
 
6096
            ),
 
6097
        RegistryOption.from_kwargs(
 
6098
            'repository_trees',
 
6099
            title='Trees in Repository',
 
6100
            help='Whether new branches in the repository have trees.',
 
6101
            value_switches=True, enum_switch=False,
 
6102
            with_trees='Reconfigure repository to create '
 
6103
                'working trees on branches by default.',
 
6104
            with_no_trees='Reconfigure repository to not create '
 
6105
                'working trees on branches by default.'
 
6106
            ),
 
6107
        Option('bind-to', help='Branch to bind checkout to.', type=str),
 
6108
        Option('force',
 
6109
            help='Perform reconfiguration even if local changes'
 
6110
            ' will be lost.'),
 
6111
        Option('stacked-on',
 
6112
            help='Reconfigure a branch to be stacked on another branch.',
 
6113
            type=text_type,
 
6114
            ),
 
6115
        Option('unstacked',
 
6116
            help='Reconfigure a branch to be unstacked.  This '
 
6117
                'may require copying substantial data into it.',
 
6118
            ),
 
6119
        ]
 
6120
 
 
6121
    def run(self, location=None, bind_to=None, force=False,
 
6122
            tree_type=None, repository_type=None, repository_trees=None,
 
6123
            stacked_on=None, unstacked=None):
 
6124
        directory = controldir.ControlDir.open(location)
 
6125
        if stacked_on and unstacked:
 
6126
            raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
 
6127
        elif stacked_on is not None:
 
6128
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
 
6129
        elif unstacked:
 
6130
            reconfigure.ReconfigureUnstacked().apply(directory)
 
6131
        # At the moment you can use --stacked-on and a different
 
6132
        # reconfiguration shape at the same time; there seems no good reason
 
6133
        # to ban it.
 
6134
        if (tree_type is None and
 
6135
            repository_type is None and
 
6136
            repository_trees is None):
 
6137
            if stacked_on or unstacked:
 
6138
                return
 
6139
            else:
 
6140
                raise errors.BzrCommandError(gettext('No target configuration '
 
6141
                    'specified'))
 
6142
        reconfiguration = None
 
6143
        if tree_type == 'branch':
 
6144
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
 
6145
        elif tree_type == 'tree':
 
6146
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
 
6147
        elif tree_type == 'checkout':
 
6148
            reconfiguration = reconfigure.Reconfigure.to_checkout(
 
6149
                directory, bind_to)
 
6150
        elif tree_type == 'lightweight-checkout':
 
6151
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
 
6152
                directory, bind_to)
 
6153
        if reconfiguration:
 
6154
            reconfiguration.apply(force)
 
6155
            reconfiguration = None
 
6156
        if repository_type == 'use-shared':
 
6157
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
 
6158
        elif repository_type == 'standalone':
 
6159
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
 
6160
        if reconfiguration:
 
6161
            reconfiguration.apply(force)
 
6162
            reconfiguration = None
 
6163
        if repository_trees == 'with-trees':
 
6164
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
6165
                directory, True)
 
6166
        elif repository_trees == 'with-no-trees':
 
6167
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
6168
                directory, False)
 
6169
        if reconfiguration:
 
6170
            reconfiguration.apply(force)
 
6171
            reconfiguration = None
 
6172
 
 
6173
 
 
6174
class cmd_switch(Command):
 
6175
    __doc__ = """Set the branch of a checkout and update.
 
6176
 
 
6177
    For lightweight checkouts, this changes the branch being referenced.
 
6178
    For heavyweight checkouts, this checks that there are no local commits
 
6179
    versus the current bound branch, then it makes the local branch a mirror
 
6180
    of the new location and binds to it.
 
6181
 
 
6182
    In both cases, the working tree is updated and uncommitted changes
 
6183
    are merged. The user can commit or revert these as they desire.
 
6184
 
 
6185
    Pending merges need to be committed or reverted before using switch.
 
6186
 
 
6187
    The path to the branch to switch to can be specified relative to the parent
 
6188
    directory of the current branch. For example, if you are currently in a
 
6189
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
 
6190
    /path/to/newbranch.
 
6191
 
 
6192
    Bound branches use the nickname of its master branch unless it is set
 
6193
    locally, in which case switching will update the local nickname to be
 
6194
    that of the master.
 
6195
    """
 
6196
 
 
6197
    takes_args = ['to_location?']
 
6198
    takes_options = ['directory',
 
6199
                     Option('force',
 
6200
                        help='Switch even if local commits will be lost.'),
 
6201
                     'revision',
 
6202
                     Option('create-branch', short_name='b',
 
6203
                        help='Create the target branch from this one before'
 
6204
                             ' switching to it.'),
 
6205
                     Option('store',
 
6206
                        help='Store and restore uncommitted changes in the'
 
6207
                             ' branch.'),
 
6208
                    ]
 
6209
 
 
6210
    def run(self, to_location=None, force=False, create_branch=False,
 
6211
            revision=None, directory=u'.', store=False):
 
6212
        from . import switch
 
6213
        tree_location = directory
 
6214
        revision = _get_one_revision('switch', revision)
 
6215
        possible_transports = []
 
6216
        control_dir = controldir.ControlDir.open_containing(tree_location,
 
6217
            possible_transports=possible_transports)[0]
 
6218
        if to_location is None:
 
6219
            if revision is None:
 
6220
                raise errors.BzrCommandError(gettext('You must supply either a'
 
6221
                                             ' revision or a location'))
 
6222
            to_location = tree_location
 
6223
        try:
 
6224
            branch = control_dir.open_branch(
 
6225
                possible_transports=possible_transports)
 
6226
            had_explicit_nick = branch.get_config().has_explicit_nickname()
 
6227
        except errors.NotBranchError:
 
6228
            branch = None
 
6229
            had_explicit_nick = False
 
6230
        if create_branch:
 
6231
            if branch is None:
 
6232
                raise errors.BzrCommandError(
 
6233
                    gettext('cannot create branch without source branch'))
 
6234
            to_location = lookup_new_sibling_branch(control_dir, to_location,
 
6235
                 possible_transports=possible_transports)
 
6236
            to_branch = branch.controldir.sprout(to_location,
 
6237
                 possible_transports=possible_transports,
 
6238
                 source_branch=branch).open_branch()
 
6239
        else:
 
6240
            try:
 
6241
                to_branch = Branch.open(to_location,
 
6242
                    possible_transports=possible_transports)
 
6243
            except errors.NotBranchError:
 
6244
                to_branch = open_sibling_branch(control_dir, to_location,
 
6245
                    possible_transports=possible_transports)
 
6246
        if revision is not None:
 
6247
            revision = revision.as_revision_id(to_branch)
 
6248
        switch.switch(control_dir, to_branch, force, revision_id=revision,
 
6249
                      store_uncommitted=store)
 
6250
        if had_explicit_nick:
 
6251
            branch = control_dir.open_branch() #get the new branch!
 
6252
            branch.nick = to_branch.nick
 
6253
        note(gettext('Switched to branch: %s'),
 
6254
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
 
6255
 
 
6256
 
 
6257
 
 
6258
class cmd_view(Command):
 
6259
    __doc__ = """Manage filtered views.
 
6260
 
 
6261
    Views provide a mask over the tree so that users can focus on
 
6262
    a subset of a tree when doing their work. After creating a view,
 
6263
    commands that support a list of files - status, diff, commit, etc -
 
6264
    effectively have that list of files implicitly given each time.
 
6265
    An explicit list of files can still be given but those files
 
6266
    must be within the current view.
 
6267
 
 
6268
    In most cases, a view has a short life-span: it is created to make
 
6269
    a selected change and is deleted once that change is committed.
 
6270
    At other times, you may wish to create one or more named views
 
6271
    and switch between them.
 
6272
 
 
6273
    To disable the current view without deleting it, you can switch to
 
6274
    the pseudo view called ``off``. This can be useful when you need
 
6275
    to see the whole tree for an operation or two (e.g. merge) but
 
6276
    want to switch back to your view after that.
 
6277
 
 
6278
    :Examples:
 
6279
      To define the current view::
 
6280
 
 
6281
        brz view file1 dir1 ...
 
6282
 
 
6283
      To list the current view::
 
6284
 
 
6285
        brz view
 
6286
 
 
6287
      To delete the current view::
 
6288
 
 
6289
        brz view --delete
 
6290
 
 
6291
      To disable the current view without deleting it::
 
6292
 
 
6293
        brz view --switch off
 
6294
 
 
6295
      To define a named view and switch to it::
 
6296
 
 
6297
        brz view --name view-name file1 dir1 ...
 
6298
 
 
6299
      To list a named view::
 
6300
 
 
6301
        brz view --name view-name
 
6302
 
 
6303
      To delete a named view::
 
6304
 
 
6305
        brz view --name view-name --delete
 
6306
 
 
6307
      To switch to a named view::
 
6308
 
 
6309
        brz view --switch view-name
 
6310
 
 
6311
      To list all views defined::
 
6312
 
 
6313
        brz view --all
 
6314
 
 
6315
      To delete all views::
 
6316
 
 
6317
        brz view --delete --all
 
6318
    """
 
6319
 
 
6320
    _see_also = []
 
6321
    takes_args = ['file*']
 
6322
    takes_options = [
 
6323
        Option('all',
 
6324
            help='Apply list or delete action to all views.',
 
6325
            ),
 
6326
        Option('delete',
 
6327
            help='Delete the view.',
 
6328
            ),
 
6329
        Option('name',
 
6330
            help='Name of the view to define, list or delete.',
 
6331
            type=text_type,
 
6332
            ),
 
6333
        Option('switch',
 
6334
            help='Name of the view to switch to.',
 
6335
            type=text_type,
 
6336
            ),
 
6337
        ]
 
6338
 
 
6339
    def run(self, file_list,
 
6340
            all=False,
 
6341
            delete=False,
 
6342
            name=None,
 
6343
            switch=None,
 
6344
            ):
 
6345
        tree, file_list = WorkingTree.open_containing_paths(file_list,
 
6346
            apply_view=False)
 
6347
        current_view, view_dict = tree.views.get_view_info()
 
6348
        if name is None:
 
6349
            name = current_view
 
6350
        if delete:
 
6351
            if file_list:
 
6352
                raise errors.BzrCommandError(gettext(
 
6353
                    "Both --delete and a file list specified"))
 
6354
            elif switch:
 
6355
                raise errors.BzrCommandError(gettext(
 
6356
                    "Both --delete and --switch specified"))
 
6357
            elif all:
 
6358
                tree.views.set_view_info(None, {})
 
6359
                self.outf.write(gettext("Deleted all views.\n"))
 
6360
            elif name is None:
 
6361
                raise errors.BzrCommandError(gettext("No current view to delete"))
 
6362
            else:
 
6363
                tree.views.delete_view(name)
 
6364
                self.outf.write(gettext("Deleted '%s' view.\n") % name)
 
6365
        elif switch:
 
6366
            if file_list:
 
6367
                raise errors.BzrCommandError(gettext(
 
6368
                    "Both --switch and a file list specified"))
 
6369
            elif all:
 
6370
                raise errors.BzrCommandError(gettext(
 
6371
                    "Both --switch and --all specified"))
 
6372
            elif switch == 'off':
 
6373
                if current_view is None:
 
6374
                    raise errors.BzrCommandError(gettext("No current view to disable"))
 
6375
                tree.views.set_view_info(None, view_dict)
 
6376
                self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
 
6377
            else:
 
6378
                tree.views.set_view_info(switch, view_dict)
 
6379
                view_str = views.view_display_str(tree.views.lookup_view())
 
6380
                self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
 
6381
        elif all:
 
6382
            if view_dict:
 
6383
                self.outf.write(gettext('Views defined:\n'))
 
6384
                for view in sorted(view_dict):
 
6385
                    if view == current_view:
 
6386
                        active = "=>"
 
6387
                    else:
 
6388
                        active = "  "
 
6389
                    view_str = views.view_display_str(view_dict[view])
 
6390
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
 
6391
            else:
 
6392
                self.outf.write(gettext('No views defined.\n'))
 
6393
        elif file_list:
 
6394
            if name is None:
 
6395
                # No name given and no current view set
 
6396
                name = 'my'
 
6397
            elif name == 'off':
 
6398
                raise errors.BzrCommandError(gettext(
 
6399
                    "Cannot change the 'off' pseudo view"))
 
6400
            tree.views.set_view(name, sorted(file_list))
 
6401
            view_str = views.view_display_str(tree.views.lookup_view())
 
6402
            self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
 
6403
        else:
 
6404
            # list the files
 
6405
            if name is None:
 
6406
                # No name given and no current view set
 
6407
                self.outf.write(gettext('No current view.\n'))
 
6408
            else:
 
6409
                view_str = views.view_display_str(tree.views.lookup_view(name))
 
6410
                self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
 
6411
 
 
6412
 
 
6413
class cmd_hooks(Command):
 
6414
    __doc__ = """Show hooks."""
 
6415
 
 
6416
    hidden = True
 
6417
 
 
6418
    def run(self):
 
6419
        for hook_key in sorted(hooks.known_hooks.keys()):
 
6420
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
 
6421
            self.outf.write("%s:\n" % type(some_hooks).__name__)
 
6422
            for hook_name, hook_point in sorted(some_hooks.items()):
 
6423
                self.outf.write("  %s:\n" % (hook_name,))
 
6424
                found_hooks = list(hook_point)
 
6425
                if found_hooks:
 
6426
                    for hook in found_hooks:
 
6427
                        self.outf.write("    %s\n" %
 
6428
                                        (some_hooks.get_hook_name(hook),))
 
6429
                else:
 
6430
                    self.outf.write(gettext("    <no hooks installed>\n"))
 
6431
 
 
6432
 
 
6433
class cmd_remove_branch(Command):
 
6434
    __doc__ = """Remove a branch.
 
6435
 
 
6436
    This will remove the branch from the specified location but 
 
6437
    will keep any working tree or repository in place.
 
6438
 
 
6439
    :Examples:
 
6440
 
 
6441
      Remove the branch at repo/trunk::
 
6442
 
 
6443
        brz remove-branch repo/trunk
 
6444
 
 
6445
    """
 
6446
 
 
6447
    takes_args = ["location?"]
 
6448
 
 
6449
    takes_options = ['directory',
 
6450
        Option('force', help='Remove branch even if it is the active branch.')]
 
6451
 
 
6452
    aliases = ["rmbranch"]
 
6453
 
 
6454
    def run(self, directory=None, location=None, force=False):
 
6455
        br = open_nearby_branch(near=directory, location=location)
 
6456
        if not force and br.controldir.has_workingtree():
 
6457
            try:
 
6458
                active_branch = br.controldir.open_branch(name="")
 
6459
            except errors.NotBranchError:
 
6460
                active_branch = None
 
6461
            if (active_branch is not None and
 
6462
                br.control_url == active_branch.control_url):
 
6463
                raise errors.BzrCommandError(
 
6464
                    gettext("Branch is active. Use --force to remove it."))
 
6465
        br.controldir.destroy_branch(br.name)
 
6466
 
 
6467
 
 
6468
class cmd_shelve(Command):
 
6469
    __doc__ = """Temporarily set aside some changes from the current tree.
 
6470
 
 
6471
    Shelve allows you to temporarily put changes you've made "on the shelf",
 
6472
    ie. out of the way, until a later time when you can bring them back from
 
6473
    the shelf with the 'unshelve' command.  The changes are stored alongside
 
6474
    your working tree, and so they aren't propagated along with your branch nor
 
6475
    will they survive its deletion.
 
6476
 
 
6477
    If shelve --list is specified, previously-shelved changes are listed.
 
6478
 
 
6479
    Shelve is intended to help separate several sets of changes that have
 
6480
    been inappropriately mingled.  If you just want to get rid of all changes
 
6481
    and you don't need to restore them later, use revert.  If you want to
 
6482
    shelve all text changes at once, use shelve --all.
 
6483
 
 
6484
    If filenames are specified, only the changes to those files will be
 
6485
    shelved. Other files will be left untouched.
 
6486
 
 
6487
    If a revision is specified, changes since that revision will be shelved.
 
6488
 
 
6489
    You can put multiple items on the shelf, and by default, 'unshelve' will
 
6490
    restore the most recently shelved changes.
 
6491
 
 
6492
    For complicated changes, it is possible to edit the changes in a separate
 
6493
    editor program to decide what the file remaining in the working copy
 
6494
    should look like.  To do this, add the configuration option
 
6495
 
 
6496
        change_editor = PROGRAM @new_path @old_path
 
6497
 
 
6498
    where @new_path is replaced with the path of the new version of the 
 
6499
    file and @old_path is replaced with the path of the old version of 
 
6500
    the file.  The PROGRAM should save the new file with the desired 
 
6501
    contents of the file in the working tree.
 
6502
        
 
6503
    """
 
6504
 
 
6505
    takes_args = ['file*']
 
6506
 
 
6507
    takes_options = [
 
6508
        'directory',
 
6509
        'revision',
 
6510
        Option('all', help='Shelve all changes.'),
 
6511
        'message',
 
6512
        RegistryOption('writer', 'Method to use for writing diffs.',
 
6513
                       breezy.option.diff_writer_registry,
 
6514
                       value_switches=True, enum_switch=False),
 
6515
 
 
6516
        Option('list', help='List shelved changes.'),
 
6517
        Option('destroy',
 
6518
               help='Destroy removed changes instead of shelving them.'),
 
6519
    ]
 
6520
    _see_also = ['unshelve', 'configuration']
 
6521
 
 
6522
    def run(self, revision=None, all=False, file_list=None, message=None,
 
6523
            writer=None, list=False, destroy=False, directory=None):
 
6524
        if list:
 
6525
            return self.run_for_list(directory=directory)
 
6526
        from .shelf_ui import Shelver
 
6527
        if writer is None:
 
6528
            writer = breezy.option.diff_writer_registry.get()
 
6529
        try:
 
6530
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
 
6531
                file_list, message, destroy=destroy, directory=directory)
 
6532
            try:
 
6533
                shelver.run()
 
6534
            finally:
 
6535
                shelver.finalize()
 
6536
        except errors.UserAbort:
 
6537
            return 0
 
6538
 
 
6539
    def run_for_list(self, directory=None):
 
6540
        if directory is None:
 
6541
            directory = u'.'
 
6542
        tree = WorkingTree.open_containing(directory)[0]
 
6543
        self.add_cleanup(tree.lock_read().unlock)
 
6544
        manager = tree.get_shelf_manager()
 
6545
        shelves = manager.active_shelves()
 
6546
        if len(shelves) == 0:
 
6547
            note(gettext('No shelved changes.'))
 
6548
            return 0
 
6549
        for shelf_id in reversed(shelves):
 
6550
            message = manager.get_metadata(shelf_id).get('message')
 
6551
            if message is None:
 
6552
                message = '<no message>'
 
6553
            self.outf.write('%3d: %s\n' % (shelf_id, message))
 
6554
        return 1
 
6555
 
 
6556
 
 
6557
class cmd_unshelve(Command):
 
6558
    __doc__ = """Restore shelved changes.
 
6559
 
 
6560
    By default, the most recently shelved changes are restored. However if you
 
6561
    specify a shelf by id those changes will be restored instead.  This works
 
6562
    best when the changes don't depend on each other.
 
6563
    """
 
6564
 
 
6565
    takes_args = ['shelf_id?']
 
6566
    takes_options = [
 
6567
        'directory',
 
6568
        RegistryOption.from_kwargs(
 
6569
            'action', help="The action to perform.",
 
6570
            enum_switch=False, value_switches=True,
 
6571
            apply="Apply changes and remove from the shelf.",
 
6572
            dry_run="Show changes, but do not apply or remove them.",
 
6573
            preview="Instead of unshelving the changes, show the diff that "
 
6574
                    "would result from unshelving.",
 
6575
            delete_only="Delete changes without applying them.",
 
6576
            keep="Apply changes but don't delete them.",
 
6577
        )
 
6578
    ]
 
6579
    _see_also = ['shelve']
 
6580
 
 
6581
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
6582
        from .shelf_ui import Unshelver
 
6583
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
6584
        try:
 
6585
            unshelver.run()
 
6586
        finally:
 
6587
            unshelver.tree.unlock()
 
6588
 
 
6589
 
 
6590
class cmd_clean_tree(Command):
 
6591
    __doc__ = """Remove unwanted files from working tree.
 
6592
 
 
6593
    By default, only unknown files, not ignored files, are deleted.  Versioned
 
6594
    files are never deleted.
 
6595
 
 
6596
    Another class is 'detritus', which includes files emitted by brz during
 
6597
    normal operations and selftests.  (The value of these files decreases with
 
6598
    time.)
 
6599
 
 
6600
    If no options are specified, unknown files are deleted.  Otherwise, option
 
6601
    flags are respected, and may be combined.
 
6602
 
 
6603
    To check what clean-tree will do, use --dry-run.
 
6604
    """
 
6605
    takes_options = ['directory',
 
6606
                     Option('ignored', help='Delete all ignored files.'),
 
6607
                     Option('detritus', help='Delete conflict files, merge and revert'
 
6608
                            ' backups, and failed selftest dirs.'),
 
6609
                     Option('unknown',
 
6610
                            help='Delete files unknown to brz (default).'),
 
6611
                     Option('dry-run', help='Show files to delete instead of'
 
6612
                            ' deleting them.'),
 
6613
                     Option('force', help='Do not prompt before deleting.')]
 
6614
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
 
6615
            force=False, directory=u'.'):
 
6616
        from .clean_tree import clean_tree
 
6617
        if not (unknown or ignored or detritus):
 
6618
            unknown = True
 
6619
        if dry_run:
 
6620
            force = True
 
6621
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
6622
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
6623
 
 
6624
 
 
6625
class cmd_reference(Command):
 
6626
    __doc__ = """list, view and set branch locations for nested trees.
 
6627
 
 
6628
    If no arguments are provided, lists the branch locations for nested trees.
 
6629
    If one argument is provided, display the branch location for that tree.
 
6630
    If two arguments are provided, set the branch location for that tree.
 
6631
    """
 
6632
 
 
6633
    hidden = True
 
6634
 
 
6635
    takes_args = ['path?', 'location?']
 
6636
 
 
6637
    def run(self, path=None, location=None):
 
6638
        branchdir = '.'
 
6639
        if path is not None:
 
6640
            branchdir = path
 
6641
        tree, branch, relpath =(
 
6642
            controldir.ControlDir.open_containing_tree_or_branch(branchdir))
 
6643
        if path is not None:
 
6644
            path = relpath
 
6645
        if tree is None:
 
6646
            tree = branch.basis_tree()
 
6647
        if path is None:
 
6648
            info = viewitems(branch._get_all_reference_info())
 
6649
            self._display_reference_info(tree, branch, info)
 
6650
        else:
 
6651
            file_id = tree.path2id(path)
 
6652
            if file_id is None:
 
6653
                raise errors.NotVersionedError(path)
 
6654
            if location is None:
 
6655
                info = [(file_id, branch.get_reference_info(file_id))]
 
6656
                self._display_reference_info(tree, branch, info)
 
6657
            else:
 
6658
                branch.set_reference_info(file_id, path, location)
 
6659
 
 
6660
    def _display_reference_info(self, tree, branch, info):
 
6661
        ref_list = []
 
6662
        for file_id, (path, location) in info:
 
6663
            try:
 
6664
                path = tree.id2path(file_id)
 
6665
            except errors.NoSuchId:
 
6666
                pass
 
6667
            ref_list.append((path, location))
 
6668
        for path, location in sorted(ref_list):
 
6669
            self.outf.write('%s %s\n' % (path, location))
 
6670
 
 
6671
 
 
6672
class cmd_export_pot(Command):
 
6673
    __doc__ = """Export command helps and error messages in po format."""
 
6674
 
 
6675
    hidden = True
 
6676
    takes_options = [Option('plugin', 
 
6677
                            help='Export help text from named command '\
 
6678
                                 '(defaults to all built in commands).',
 
6679
                            type=str),
 
6680
                     Option('include-duplicates',
 
6681
                            help='Output multiple copies of the same msgid '
 
6682
                                 'string if it appears more than once.'),
 
6683
                            ]
 
6684
 
 
6685
    def run(self, plugin=None, include_duplicates=False):
 
6686
        from .export_pot import export_pot
 
6687
        export_pot(self.outf, plugin, include_duplicates)
 
6688
 
 
6689
 
 
6690
class cmd_import(Command):
 
6691
    __doc__ = """Import sources from a directory, tarball or zip file
 
6692
 
 
6693
    This command will import a directory, tarball or zip file into a bzr
 
6694
    tree, replacing any versioned files already present.  If a directory is
 
6695
    specified, it is used as the target.  If the directory does not exist, or
 
6696
    is not versioned, it is created.
 
6697
 
 
6698
    Tarballs may be gzip or bzip2 compressed.  This is autodetected.
 
6699
 
 
6700
    If the tarball or zip has a single root directory, that directory is
 
6701
    stripped when extracting the tarball.  This is not done for directories.
 
6702
    """
 
6703
 
 
6704
    takes_args = ['source', 'tree?']
 
6705
 
 
6706
    def run(self, source, tree=None):
 
6707
        from .upstream_import import do_import
 
6708
        do_import(source, tree)
 
6709
 
 
6710
 
 
6711
class cmd_fetch_ghosts(Command):
 
6712
    __doc__ = """Attempt to retrieve ghosts from another branch.
 
6713
 
 
6714
    If the other branch is not supplied, the last-pulled branch is used.
 
6715
    """
 
6716
 
 
6717
    hidden = True
 
6718
    aliases = ['fetch-missing']
 
6719
    takes_args = ['branch?']
 
6720
    takes_options = [Option('no-fix', help="Skip additional synchonization.")]
 
6721
 
 
6722
    def run(self, branch=None, no_fix=False):
 
6723
        from .fetch_ghosts import GhostFetcher
 
6724
        installed, failed = GhostFetcher.from_cmdline(branch).run()
 
6725
        if len(installed) > 0:
 
6726
            self.outf.write("Installed:\n")
 
6727
            for rev in installed:
 
6728
                self.outf.write(rev + "\n")
 
6729
        if len(failed) > 0:
 
6730
            self.outf.write("Still missing:\n")
 
6731
            for rev in failed:
 
6732
                self.outf.write(rev + "\n")
 
6733
        if not no_fix and len(installed) > 0:
 
6734
            cmd_reconcile().run(".")
 
6735
 
 
6736
 
 
6737
def _register_lazy_builtins():
 
6738
    # register lazy builtins from other modules; called at startup and should
 
6739
    # be only called once.
 
6740
    for (name, aliases, module_name) in [
 
6741
        ('cmd_bisect', [], 'breezy.bisect'),
 
6742
        ('cmd_bundle_info', [], 'breezy.bundle.commands'),
 
6743
        ('cmd_config', [], 'breezy.config'),
 
6744
        ('cmd_dpush', [], 'breezy.foreign'),
 
6745
        ('cmd_version_info', [], 'breezy.cmd_version_info'),
 
6746
        ('cmd_resolve', ['resolved'], 'breezy.conflicts'),
 
6747
        ('cmd_conflicts', [], 'breezy.conflicts'),
 
6748
        ('cmd_ping', [], 'breezy.bzr.smart.ping'),
 
6749
        ('cmd_sign_my_commits', [], 'breezy.commit_signature_commands'),
 
6750
        ('cmd_verify_signatures', [], 'breezy.commit_signature_commands'),
 
6751
        ('cmd_test_script', [], 'breezy.cmd_test_script'),
 
6752
        ]:
 
6753
        builtin_command_registry.register_lazy(name, aliases, module_name)