/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: Jelmer Vernooij
  • Date: 2018-04-01 17:37:15 UTC
  • mto: This revision was merged to the branch mainline in revision 6931.
  • Revision ID: jelmer@jelmer.uk-20180401173715-rh4obuk6uj2bjyb3
README -> README.rst in more places.

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