/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 bzrlib/builtins.py

  • Committer: Martin Packman
  • Date: 2011-10-06 16:41:45 UTC
  • mfrom: (6015.33.10 2.4)
  • mto: This revision was merged to the branch mainline in revision 6202.
  • Revision ID: martin.packman@canonical.com-20111006164145-o98oqn32440extgt
Merge 2.4 into dev

Show diffs side-by-side

added added

removed removed

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