/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: Andrew Bennetts
  • Date: 2010-10-13 06:14:37 UTC
  • mto: This revision was merged to the branch mainline in revision 5498.
  • Revision ID: andrew.bennetts@canonical.com-20101013061437-2e2m9gro1eusnbb8
Tweaks to the sphinx build.

Show diffs side-by-side

added added

removed removed

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