/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Martin Pool
  • Date: 2010-07-16 15:20:17 UTC
  • mfrom: (5346.3.1 pathnotchild)
  • mto: This revision was merged to the branch mainline in revision 5351.
  • Revision ID: mbp@canonical.com-20100716152017-t4c73h9y1uoih7fb
PathNotChild should not give a traceback.

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