~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

Move doctest import to increase speed

Show diffs side-by-side

added added

removed removed

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