/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: 2019-06-03 23:48:08 UTC
  • mfrom: (7316 work)
  • mto: This revision was merged to the branch mainline in revision 7328.
  • Revision ID: jelmer@jelmer.uk-20190603234808-15yk5c7054tj8e2b
Merge trunk.

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