~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-07-12 12:36:57 UTC
  • mfrom: (1732.3.4 bzr.revnoX)
  • Revision ID: pqm@pqm.ubuntu.com-20060712123657-365eeb32b69308bf
(matthieu) revno:x:url revision spec

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
import os.path
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
 
    )
56
 
from bzrlib.branch import Branch
 
27
from bzrlib.branch import Branch, BranchReferenceFormat
 
28
from bzrlib import (bundle, branch, bzrdir, errors, osutils, ui, config,
 
29
    repository, log)
 
30
from bzrlib.bundle import read_bundle_from_url
 
31
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
57
32
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
 
33
from bzrlib.commands import Command, display_command
 
34
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError, 
 
35
                           NotBranchError, DivergedBranches, NotConflicted,
 
36
                           NoSuchFile, NoWorkingTree, FileInWrongBranch,
 
37
                           NotVersionedError, NotABundle)
 
38
from bzrlib.merge import Merge3Merger
 
39
from bzrlib.option import Option
 
40
from bzrlib.progress import DummyProgress, ProgressPhase
 
41
from bzrlib.revision import common_ancestor
 
42
from bzrlib.revisionspec import RevisionSpec
 
43
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
 
44
from bzrlib.transport.local import LocalTransport
 
45
import bzrlib.urlutils as urlutils
61
46
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
 
47
 
 
48
 
 
49
def tree_files(file_list, default_branch=u'.'):
 
50
    try:
 
51
        return internal_tree_files(file_list, default_branch)
 
52
    except FileInWrongBranch, e:
 
53
        raise BzrCommandError("%s is not in the same branch as %s" %
 
54
                             (e.path, file_list[0]))
149
55
 
150
56
 
151
57
# XXX: Bad function name; should possibly also be a class method of
152
58
# 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):
 
59
def internal_tree_files(file_list, default_branch=u'.'):
156
60
    """Convert command-line paths to a WorkingTree and relative paths.
157
61
 
158
 
    Deprecated: use WorkingTree.open_containing_paths instead.
159
 
 
160
62
    This is typically used for command-line processors that take one or
161
63
    more filenames, and infer the workingtree that contains them.
162
64
 
163
65
    The filenames given are not required to exist.
164
66
 
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
 
67
    :param file_list: Filenames to convert.  
 
68
 
 
69
    :param default_branch: Fallback tree path to use if file_list is empty or None.
172
70
 
173
71
    :return: workingtree, [relative_paths]
174
72
    """
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)
 
73
    if file_list is None or len(file_list) == 0:
 
74
        return WorkingTree.open_containing(default_branch)[0], file_list
 
75
    tree = WorkingTree.open_containing(file_list[0])[0]
 
76
    new_list = []
 
77
    for filename in file_list:
 
78
        try:
 
79
            new_list.append(tree.relpath(filename))
 
80
        except errors.PathNotChild:
 
81
            raise FileInWrongBranch(tree.branch, filename)
 
82
    return tree, new_list
 
83
 
 
84
 
 
85
def get_format_type(typestring):
 
86
    """Parse and return a format specifier."""
 
87
    if typestring == "weave":
 
88
        return bzrdir.BzrDirFormat6()
 
89
    if typestring == "default":
 
90
        return bzrdir.BzrDirMetaFormat1()
 
91
    if typestring == "metaweave":
 
92
        format = bzrdir.BzrDirMetaFormat1()
 
93
        format.repository_format = repository.RepositoryFormat7()
 
94
        return format
 
95
    if typestring == "knit":
 
96
        format = bzrdir.BzrDirMetaFormat1()
 
97
        format.repository_format = repository.RepositoryFormatKnit1()
 
98
        return format
 
99
    msg = "Unknown bzr format %s. Current formats are: default, knit,\n" \
 
100
          "metaweave and weave" % typestring
 
101
    raise BzrCommandError(msg)
199
102
 
200
103
 
201
104
# TODO: Make sure no commands unconditionally use the working directory as a
205
108
# opens the branch?)
206
109
 
207
110
class cmd_status(Command):
208
 
    __doc__ = """Display status summary.
 
111
    """Display status summary.
209
112
 
210
113
    This reports on versioned and unknown files, reporting them
211
114
    grouped by state.  Possible states are:
225
128
    modified
226
129
        Text has changed since the previous revision.
227
130
 
228
 
    kind changed
229
 
        File kind has been changed (e.g. from file to directory).
230
 
 
231
131
    unknown
232
132
        Not versioned and not matching an ignore pattern.
233
133
 
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
 
134
    To see ignored files use 'bzr ignored'.  For details in the
239
135
    changes to file texts, use 'bzr diff'.
240
136
 
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
137
    If no arguments are specified, the status of the entire working
246
138
    directory is shown.  Otherwise, only the status of the specified
247
139
    files or directories is reported.  If a directory is given, status
248
140
    is reported for everything inside that directory.
249
141
 
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'.
 
142
    If a revision argument is given, the status is calculated against
 
143
    that revision, or between two revisions if two are provided.
261
144
    """
262
 
 
 
145
    
263
146
    # TODO: --no-recurse, --recurse options
264
 
 
 
147
    
265
148
    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
 
                     ]
 
149
    takes_options = ['show-ids', 'revision']
274
150
    aliases = ['st', 'stat']
275
151
 
276
152
    encoding_type = 'replace'
277
 
    _see_also = ['diff', 'revert', 'status-flags']
278
 
 
 
153
    
279
154
    @display_command
280
 
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
281
 
            versioned=False, no_pending=False, verbose=False):
 
155
    def run(self, show_ids=False, file_list=None, revision=None):
282
156
        from bzrlib.status import show_tree_status
283
157
 
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
 
158
        tree, file_list = tree_files(file_list)
 
159
            
298
160
        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)
 
161
                         specific_files=file_list, revision=revision,
 
162
                         to_file=self.outf)
302
163
 
303
164
 
304
165
class cmd_cat_revision(Command):
305
 
    __doc__ = """Write out metadata for a revision.
306
 
 
 
166
    """Write out metadata for a revision.
 
167
    
307
168
    The revision to print can either be specified by a specific
308
169
    revision identifier, or you can use --revision.
309
170
    """
310
171
 
311
172
    hidden = True
312
173
    takes_args = ['revision_id?']
313
 
    takes_options = ['directory', 'revision']
 
174
    takes_options = ['revision']
314
175
    # cat-revision is more for frontends so should be exact
315
176
    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
 
 
 
177
    
325
178
    @display_command
326
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
179
    def run(self, revision_id=None, revision=None):
 
180
 
327
181
        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')
 
182
            raise BzrCommandError('You can only supply one of revision_id or --revision')
330
183
        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
 
 
 
184
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
185
        b = WorkingTree.open_containing(u'.')[0].branch
 
186
 
 
187
        # TODO: jam 20060112 should cat-revision always output utf-8?
 
188
        if revision_id is not None:
 
189
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
190
        elif revision is not None:
 
191
            for rev in revision:
 
192
                if rev is None:
 
193
                    raise BzrCommandError('You cannot specify a NULL revision.')
 
194
                revno, rev_id = rev.in_history(b)
 
195
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
 
196
    
485
197
 
486
198
class cmd_revno(Command):
487
 
    __doc__ = """Show current revision number.
 
199
    """Show current revision number.
488
200
 
489
201
    This is equal to the number of revisions on this branch.
490
202
    """
491
203
 
492
 
    _see_also = ['info']
493
204
    takes_args = ['location?']
494
 
    takes_options = [
495
 
        Option('tree', help='Show revno of working tree'),
496
 
        ]
497
205
 
498
206
    @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')
 
207
    def run(self, location=u'.'):
 
208
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
 
209
        self.outf.write('\n')
518
210
 
519
211
 
520
212
class cmd_revision_info(Command):
521
 
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
213
    """Show revision number and revision id for a given revision identifier.
522
214
    """
523
215
    hidden = True
524
216
    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
 
        ]
 
217
    takes_options = ['revision']
532
218
 
533
219
    @display_command
534
 
    def run(self, revision=None, directory=u'.', tree=False,
535
 
            revision_info_list=[]):
 
220
    def run(self, revision=None, revision_info_list=[]):
536
221
 
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 = []
 
222
        revs = []
546
223
        if revision is not None:
547
 
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
 
224
            revs.extend(revision)
548
225
        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())
 
226
            for rev in revision_info_list:
 
227
                revs.append(RevisionSpec(rev))
 
228
        if len(revs) == 0:
 
229
            raise BzrCommandError('You must supply a revision identifier')
 
230
 
 
231
        b = WorkingTree.open_containing(u'.')[0].branch
 
232
 
 
233
        for rev in revs:
 
234
            revinfo = rev.in_history(b)
 
235
            if revinfo.revno is None:
 
236
                print '     %s' % revinfo.rev_id
558
237
            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
 
 
 
238
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
239
 
 
240
    
577
241
class cmd_add(Command):
578
 
    __doc__ = """Add specified files or directories.
 
242
    """Add specified files or directories.
579
243
 
580
244
    In non-recursive mode, all the named items are added, regardless
581
245
    of whether they were previously ignored.  A warning is given if
597
261
    you should never need to explicitly add a directory, they'll just
598
262
    get added when you add a file in the directory.
599
263
 
600
 
    --dry-run will show which files would be added, but not actually
 
264
    --dry-run will show which files would be added, but not actually 
601
265
    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
266
    """
614
267
    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
 
        ]
 
268
    takes_options = ['no-recurse', 'dry-run', 'verbose']
625
269
    encoding_type = 'replace'
626
 
    _see_also = ['remove', 'ignore']
627
270
 
628
 
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
629
 
            file_ids_from=None):
 
271
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False):
630
272
        import bzrlib.add
631
273
 
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()
 
274
        action = bzrlib.add.AddAction(to_file=self.outf,
 
275
            should_print=(not is_quiet()))
 
276
 
 
277
        added, ignored = bzrlib.add.smart_add(file_list, not no_recurse, 
 
278
                                              action=action, save=not dry_run)
654
279
        if len(ignored) > 0:
655
280
            if verbose:
656
281
                for glob in sorted(ignored.keys()):
657
282
                    for path in ignored[glob]:
658
 
                        self.outf.write("ignored %s matching \"%s\"\n"
 
283
                        self.outf.write("ignored %s matching \"%s\"\n" 
659
284
                                        % (path, glob))
 
285
            else:
 
286
                match_len = 0
 
287
                for glob, paths in ignored.items():
 
288
                    match_len += len(paths)
 
289
                self.outf.write("ignored %d file(s).\n" % match_len)
 
290
            self.outf.write("If you wish to add some of these files,"
 
291
                            " please add them by name.\n")
660
292
 
661
293
 
662
294
class cmd_mkdir(Command):
663
 
    __doc__ = """Create a new versioned directory.
 
295
    """Create a new versioned directory.
664
296
 
665
297
    This is equivalent to creating the directory and then adding it.
666
298
    """
670
302
 
671
303
    def run(self, dir_list):
672
304
        for d in dir_list:
 
305
            os.mkdir(d)
673
306
            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)
 
307
            wt.add([dd])
 
308
            self.outf.write('added %s\n' % d)
682
309
 
683
310
 
684
311
class cmd_relpath(Command):
685
 
    __doc__ = """Show path of a file relative to root"""
 
312
    """Show path of a file relative to root"""
686
313
 
687
314
    takes_args = ['filename']
688
315
    hidden = True
689
 
 
 
316
    
690
317
    @display_command
691
318
    def run(self, filename):
692
319
        # TODO: jam 20050106 Can relpath return a munged path if
697
324
 
698
325
 
699
326
class cmd_inventory(Command):
700
 
    __doc__ = """Show inventory of the current working copy or a revision.
 
327
    """Show inventory of the current working copy or a revision.
701
328
 
702
329
    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
 
330
    type using the --kind option.  For example; --kind file.
707
331
    """
708
332
 
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
 
 
 
333
    takes_options = ['revision', 'show-ids', 'kind']
 
334
    
720
335
    @display_command
721
 
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
 
336
    def run(self, revision=None, show_ids=False, kind=None):
722
337
        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:
 
338
            raise BzrCommandError('invalid kind specified')
 
339
        tree = WorkingTree.open_containing(u'.')[0]
 
340
        if revision is None:
 
341
            inv = tree.read_working_inventory()
 
342
        else:
 
343
            if len(revision) > 1:
 
344
                raise BzrCommandError('bzr inventory --revision takes'
 
345
                    ' exactly one revision identifier')
 
346
            inv = tree.branch.repository.get_revision_inventory(
 
347
                revision[0].in_history(tree.branch).rev_id)
 
348
 
 
349
        for path, entry in inv.entries():
749
350
            if kind and kind != entry.kind:
750
351
                continue
751
352
            if show_ids:
756
357
 
757
358
 
758
359
class cmd_mv(Command):
759
 
    __doc__ = """Move or rename a file.
 
360
    """Move or rename a file.
760
361
 
761
 
    :Usage:
 
362
    usage:
762
363
        bzr mv OLDNAME NEWNAME
763
 
 
764
364
        bzr mv SOURCE... DESTINATION
765
365
 
766
366
    If the last argument is a versioned directory, all the other names
767
367
    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.
 
368
    and the file is changed to a new name, which must not already exist.
775
369
 
776
370
    Files cannot be moved between branches.
777
371
    """
778
372
 
779
373
    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
374
    aliases = ['move', 'rename']
786
375
    encoding_type = 'replace'
787
376
 
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.')
 
377
    def run(self, names_list):
793
378
        if names_list is None:
794
379
            names_list = []
 
380
 
795
381
        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:
 
382
            raise BzrCommandError("missing file argument")
 
383
        tree, rel_names = tree_files(names_list)
 
384
        
 
385
        if os.path.isdir(names_list[-1]):
834
386
            # 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))
 
387
            for pair in tree.move(rel_names[:-1], rel_names[-1]):
 
388
                self.outf.write("%s => %s\n" % pair)
841
389
        else:
842
390
            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
 
 
 
391
                raise BzrCommandError('to mv multiple files the destination '
 
392
                                      'must be a versioned directory')
 
393
            tree.rename_one(rel_names[0], rel_names[1])
 
394
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
 
395
            
 
396
    
894
397
class cmd_pull(Command):
895
 
    __doc__ = """Turn this branch into a mirror of another branch.
 
398
    """Turn this branch into a mirror of another branch.
896
399
 
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.
 
400
    This command only works on branches that have not diverged.  Branches are
 
401
    considered diverged if the destination branch's most recent commit is one
 
402
    that has not been merged (directly or indirectly) into the parent.
901
403
 
902
404
    If branches have diverged, you can use 'bzr merge' to integrate the changes
903
405
    from one into the other.  Once one branch has merged, the other should
904
406
    be able to pull it again.
905
407
 
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.
 
408
    If you want to forget your local changes and just update your branch to
 
409
    match the remote one, use pull --overwrite.
909
410
 
910
411
    If there is no default location set, the first pull will set it.  After
911
412
    that, you can omit the location to use the default.  To change the
912
413
    default, use --remember. The value will only be saved if the remote
913
414
    location can be accessed.
914
 
 
915
 
    Note: The location can be specified either in the form of a branch,
916
 
    or in the form of a path to a file containing a merge directive generated
917
 
    with bzr send.
918
415
    """
919
416
 
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
 
        ]
 
417
    takes_options = ['remember', 'overwrite', 'revision', 'verbose']
935
418
    takes_args = ['location?']
936
419
    encoding_type = 'replace'
937
420
 
938
 
    def run(self, location=None, remember=False, overwrite=False,
939
 
            revision=None, verbose=False,
940
 
            directory=None, local=False,
941
 
            show_base=False):
 
421
    def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
942
422
        # 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
423
        try:
948
 
            tree_to = WorkingTree.open_containing(directory)[0]
 
424
            tree_to = WorkingTree.open_containing(u'.')[0]
949
425
            branch_to = tree_to.branch
950
 
            self.add_cleanup(tree_to.lock_write().unlock)
951
 
        except errors.NoWorkingTree:
 
426
        except NoWorkingTree:
952
427
            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 = []
 
428
            branch_to = Branch.open_containing(u'.')[0]
 
429
 
 
430
        reader = None
963
431
        if location is not None:
964
432
            try:
965
 
                mergeable = bundle.read_mergeable_from_url(location,
966
 
                    possible_transports=possible_transports)
967
 
            except errors.NotABundle:
968
 
                mergeable = None
 
433
                reader = bundle.read_bundle_from_url(location)
 
434
            except NotABundle:
 
435
                pass # Continue on considering this url a Branch
969
436
 
970
437
        stored_loc = branch_to.get_parent()
971
438
        if location is None:
972
439
            if stored_loc is None:
973
 
                raise errors.BzrCommandError("No pull location known or"
974
 
                                             " specified.")
 
440
                raise BzrCommandError("No pull location known or specified.")
975
441
            else:
976
442
                display_url = urlutils.unescape_for_display(stored_loc,
977
443
                        self.outf.encoding)
978
 
                if not is_quiet():
979
 
                    self.outf.write("Using saved parent location: %s\n" % display_url)
 
444
                self.outf.write("Using saved location: %s\n" % display_url)
980
445
                location = stored_loc
981
446
 
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)
 
447
 
 
448
        if reader is not None:
 
449
            install_bundle(branch_to.repository, reader)
990
450
            branch_from = branch_to
991
451
        else:
992
 
            branch_from = Branch.open(location,
993
 
                possible_transports=possible_transports)
994
 
            self.add_cleanup(branch_from.lock_read().unlock)
 
452
            branch_from = Branch.open(location)
995
453
 
996
454
            if branch_to.get_parent() is None or remember:
997
455
                branch_to.set_parent(branch_from.base)
998
456
 
999
 
        if revision is not None:
1000
 
            revision_id = revision.as_revision_id(branch_from)
 
457
        rev_id = None
 
458
        if revision is None:
 
459
            if reader is not None:
 
460
                rev_id = reader.target
 
461
        elif len(revision) == 1:
 
462
            rev_id = revision[0].in_history(branch_from).rev_id
 
463
        else:
 
464
            raise BzrCommandError('bzr pull --revision takes one value.')
1001
465
 
 
466
        old_rh = branch_to.revision_history()
1002
467
        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)
 
468
            count = tree_to.pull(branch_from, overwrite, rev_id)
1011
469
        else:
1012
 
            result = branch_to.pull(
1013
 
                branch_from, overwrite, revision_id, local=local)
 
470
            count = branch_to.pull(branch_from, overwrite, rev_id)
 
471
        note('%d revision(s) pulled.' % (count,))
1014
472
 
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)
 
473
        if verbose:
 
474
            new_rh = branch_to.revision_history()
 
475
            if old_rh != new_rh:
 
476
                # Something changed
 
477
                from bzrlib.log import show_changed_revisions
 
478
                show_changed_revisions(branch_to, old_rh, new_rh,
 
479
                                       to_file=self.outf)
1020
480
 
1021
481
 
1022
482
class cmd_push(Command):
1023
 
    __doc__ = """Update a mirror of this branch.
1024
 
 
 
483
    """Update a mirror of this branch.
 
484
    
1025
485
    The target branch will not have its working tree populated because this
1026
486
    is both expensive, and is not supported on remote file systems.
1027
 
 
 
487
    
1028
488
    Some smart servers or protocols *may* put the working tree in place in
1029
489
    the future.
1030
490
 
1034
494
 
1035
495
    If branches have diverged, you can use 'bzr push --overwrite' to replace
1036
496
    the other branch completely, discarding its unmerged changes.
1037
 
 
 
497
    
1038
498
    If you want to ensure you have the different changes in the other branch,
1039
499
    do a merge (see bzr help merge) from the other branch, and commit that.
1040
500
    After that you will be able to do a push without '--overwrite'.
1045
505
    location can be accessed.
1046
506
    """
1047
507
 
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
 
        ]
 
508
    takes_options = ['remember', 'overwrite', 'verbose',
 
509
                     Option('create-prefix', 
 
510
                            help='Create the path leading up to the branch '
 
511
                                 'if it does not already exist')]
1076
512
    takes_args = ['location?']
1077
513
    encoding_type = 'replace'
1078
514
 
1079
515
    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
 
516
            create_prefix=False, verbose=False):
 
517
        # FIXME: Way too big!  Put this into a function called from the
 
518
        # command.
 
519
        from bzrlib.transport import get_transport
 
520
        
 
521
        br_from = Branch.open_containing('.')[0]
 
522
        stored_loc = br_from.get_push_location()
1120
523
        if location is None:
1121
 
            stored_loc = br_from.get_push_location()
1122
524
            if stored_loc is None:
1123
 
                raise errors.BzrCommandError(
1124
 
                    "No push location known or specified.")
 
525
                raise BzrCommandError("No push location known or specified.")
1125
526
            else:
1126
527
                display_url = urlutils.unescape_for_display(stored_loc,
1127
528
                        self.outf.encoding)
1128
 
                self.outf.write("Using saved push location: %s\n" % display_url)
 
529
                self.outf.write("Using saved location: %s\n" % display_url)
1129
530
                location = stored_loc
1130
531
 
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)
 
532
        transport = get_transport(location)
 
533
        location_url = transport.base
 
534
 
 
535
        old_rh = []
 
536
        try:
 
537
            dir_to = bzrdir.BzrDir.open(location_url)
 
538
            br_to = dir_to.open_branch()
 
539
        except NotBranchError:
 
540
            # create a branch.
 
541
            transport = transport.clone('..')
 
542
            if not create_prefix:
 
543
                try:
 
544
                    relurl = transport.relpath(location_url)
 
545
                    mutter('creating directory %s => %s', location_url, relurl)
 
546
                    transport.mkdir(relurl)
 
547
                except NoSuchFile:
 
548
                    raise BzrCommandError("Parent directory of %s "
 
549
                                          "does not exist." % location)
 
550
            else:
 
551
                current = transport.base
 
552
                needed = [(transport, transport.relpath(location_url))]
 
553
                while needed:
 
554
                    try:
 
555
                        transport, relpath = needed[-1]
 
556
                        transport.mkdir(relpath)
 
557
                        needed.pop()
 
558
                    except NoSuchFile:
 
559
                        new_transport = transport.clone('..')
 
560
                        needed.append((new_transport,
 
561
                                       new_transport.relpath(transport.base)))
 
562
                        if new_transport.base == transport.base:
 
563
                            raise BzrCommandError("Could not create "
 
564
                                                  "path prefix.")
 
565
            dir_to = br_from.bzrdir.clone(location_url,
 
566
                revision_id=br_from.last_revision())
 
567
            br_to = dir_to.open_branch()
 
568
            count = len(br_to.revision_history())
 
569
            # We successfully created the target, remember it
 
570
            if br_from.get_push_location() is None or remember:
 
571
                br_from.set_push_location(br_to.base)
 
572
        else:
 
573
            # We were able to connect to the remote location, so remember it
 
574
            # we don't need to successfully push because of possible divergence.
 
575
            if br_from.get_push_location() is None or remember:
 
576
                br_from.set_push_location(br_to.base)
 
577
            old_rh = br_to.revision_history()
 
578
            try:
 
579
                try:
 
580
                    tree_to = dir_to.open_workingtree()
 
581
                except errors.NotLocalUrl:
 
582
                    warning('This transport does not update the working '
 
583
                            'tree of: %s' % (br_to.base,))
 
584
                    count = br_to.pull(br_from, overwrite)
 
585
                except NoWorkingTree:
 
586
                    count = br_to.pull(br_from, overwrite)
 
587
                else:
 
588
                    count = tree_to.pull(br_from, overwrite)
 
589
            except DivergedBranches:
 
590
                raise BzrCommandError("These branches have diverged."
 
591
                                      "  Try a merge then push with overwrite.")
 
592
        note('%d revision(s) pushed.' % (count,))
 
593
 
 
594
        if verbose:
 
595
            new_rh = br_to.revision_history()
 
596
            if old_rh != new_rh:
 
597
                # Something changed
 
598
                from bzrlib.log import show_changed_revisions
 
599
                show_changed_revisions(br_to, old_rh, new_rh,
 
600
                                       to_file=self.outf)
1135
601
 
1136
602
 
1137
603
class cmd_branch(Command):
1138
 
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
604
    """Create a new copy of a branch.
1139
605
 
1140
606
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1141
607
    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
608
 
1147
609
    To retrieve the branch as of a particular revision, supply the --revision
1148
610
    parameter, as in "branch foo/bar -r 5".
 
611
 
 
612
    --basis is to speed up branching from remote branches.  When specified, it
 
613
    copies all the file-contents, inventory and revision data from the basis
 
614
    branch before copying anything from the remote branch.
1149
615
    """
1150
 
 
1151
 
    _see_also = ['checkout']
1152
616
    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
 
        ]
 
617
    takes_options = ['revision', 'basis']
1176
618
    aliases = ['get', 'clone']
1177
619
 
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:
 
620
    def run(self, from_location, to_location=None, revision=None, basis=None):
 
621
        from bzrlib.transport import get_transport
 
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 errors.FileExists:
 
658
                raise BzrCommandError('Target directory "%s" already'
 
659
                                      ' exists.' % to_location)
 
660
            except 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 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 errors.UnlistableBranch:
 
673
                osutils.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
713
    aliases = ['co']
1297
714
 
1298
 
    def run(self, branch_location=None, to_location=None, revision=None,
1299
 
            lightweight=False, files_from=None, hardlink=False):
 
715
    def run(self, branch_location=None, to_location=None, revision=None, basis=None,
 
716
            lightweight=False):
 
717
        if revision is None:
 
718
            revision = [None]
 
719
        elif len(revision) > 1:
 
720
            raise BzrCommandError(
 
721
                'bzr checkout --revision takes exactly 1 revision value')
1300
722
        if branch_location is None:
1301
723
            branch_location = osutils.getcwd()
1302
724
            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)
 
725
        source = Branch.open(branch_location)
 
726
        if len(revision) == 1 and revision[0] is not None:
 
727
            revision_id = revision[0].in_history(source)[1]
1315
728
        else:
1316
729
            revision_id = None
1317
730
        if to_location is None:
1318
 
            to_location = urlutils.derive_to_location(branch_location)
1319
 
        # if the source and to_location are the same,
 
731
            to_location = os.path.basename(branch_location.rstrip("/\\"))
 
732
        # if the source and to_location are the same, 
1320
733
        # and there is no working tree,
1321
734
        # then reconstitute a branch
1322
 
        if (osutils.abspath(to_location) ==
 
735
        if (osutils.abspath(to_location) == 
1323
736
            osutils.abspath(branch_location)):
1324
737
            try:
1325
738
                source.bzrdir.open_workingtree()
1326
739
            except errors.NoWorkingTree:
1327
 
                source.bzrdir.create_workingtree(revision_id)
 
740
                source.bzrdir.create_workingtree()
1328
741
                return
1329
 
        source.create_checkout(to_location, revision_id, lightweight,
1330
 
                               accelerator_tree, hardlink)
 
742
        try:
 
743
            os.mkdir(to_location)
 
744
        except OSError, e:
 
745
            if e.errno == errno.EEXIST:
 
746
                raise BzrCommandError('Target directory "%s" already'
 
747
                                      ' exists.' % to_location)
 
748
            if e.errno == errno.ENOENT:
 
749
                raise BzrCommandError('Parent of "%s" does not exist.' %
 
750
                                      to_location)
 
751
            else:
 
752
                raise
 
753
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
754
        bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
 
755
        try:
 
756
            if lightweight:
 
757
                checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
 
758
                branch.BranchReferenceFormat().initialize(checkout, source)
 
759
            else:
 
760
                checkout_branch =  bzrdir.BzrDir.create_branch_convenience(
 
761
                    to_location, force_new_tree=False)
 
762
                checkout = checkout_branch.bzrdir
 
763
                checkout_branch.bind(source)
 
764
                if revision_id is not None:
 
765
                    rh = checkout_branch.revision_history()
 
766
                    checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
 
767
            checkout.create_workingtree(revision_id)
 
768
        finally:
 
769
            bzrdir.BzrDirFormat.set_default_format(old_format)
1331
770
 
1332
771
 
1333
772
class cmd_renames(Command):
1334
 
    __doc__ = """Show list of renamed files.
 
773
    """Show list of renamed files.
1335
774
    """
1336
775
    # TODO: Option to show renames between two historical versions.
1337
776
 
1338
777
    # TODO: Only show renames under dir, rather than in the whole branch.
1339
 
    _see_also = ['status']
1340
778
    takes_args = ['dir?']
1341
779
 
1342
780
    @display_command
1343
781
    def run(self, dir=u'.'):
 
782
        from bzrlib.tree import find_renames
1344
783
        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)
 
784
        old_inv = tree.basis_tree().inventory
 
785
        new_inv = tree.read_working_inventory()
 
786
        renames = list(find_renames(old_inv, new_inv))
1358
787
        renames.sort()
1359
788
        for old_name, new_name in renames:
1360
789
            self.outf.write("%s => %s\n" % (old_name, new_name))
1361
790
 
1362
791
 
1363
792
class cmd_update(Command):
1364
 
    __doc__ = """Update a tree to have the latest code committed to its branch.
1365
 
 
 
793
    """Update a tree to have the latest code committed to its branch.
 
794
    
1366
795
    This will perform a merge into the working tree, and may generate
1367
 
    conflicts. If you have any local changes, you will still
 
796
    conflicts. If you have any local changes, you will still 
1368
797
    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
 
798
    
 
799
    If you want to discard your local changes, you can just do a 
1371
800
    '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
801
    """
1379
 
 
1380
 
    _see_also = ['pull', 'working-trees', 'status-flags']
1381
802
    takes_args = ['dir?']
1382
 
    takes_options = ['revision',
1383
 
                     Option('show-base',
1384
 
                            help="Show base revision text in conflicts."),
1385
 
                     ]
1386
 
    aliases = ['up']
1387
803
 
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")
 
804
    def run(self, dir='.'):
1392
805
        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)
 
806
        tree.lock_write()
1429
807
        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
 
808
            last_rev = tree.last_revision() 
 
809
            if last_rev == tree.branch.last_revision():
 
810
                # may be up to date, check master too.
 
811
                master = tree.branch.get_master_branch()
 
812
                if master is None or last_rev == master.last_revision():
 
813
                    revno = tree.branch.revision_id_to_revno(last_rev)
 
814
                    note("Tree is up to date at revision %d." % (revno,))
 
815
                    return 0
 
816
            conflicts = tree.update()
 
817
            revno = tree.branch.revision_id_to_revno(tree.last_revision())
 
818
            note('Updated to revision %d.' % (revno,))
 
819
            if conflicts != 0:
 
820
                return 1
 
821
            else:
 
822
                return 0
 
823
        finally:
 
824
            tree.unlock()
1454
825
 
1455
826
 
1456
827
class cmd_info(Command):
1457
 
    __doc__ = """Show information about a working tree, branch or repository.
 
828
    """Show information about a working tree, branch or repository.
1458
829
 
1459
830
    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.
 
831
    tree, branch or repository.  Statistical information is included with
 
832
    each report.
1465
833
 
1466
834
    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
835
    """
1484
 
    _see_also = ['revno', 'working-trees', 'repositories']
1485
836
    takes_args = ['location?']
1486
837
    takes_options = ['verbose']
1487
 
    encoding_type = 'replace'
1488
838
 
1489
839
    @display_command
1490
840
    def run(self, location=None, verbose=False):
1491
 
        if verbose:
1492
 
            noise_level = get_verbosity_level()
1493
 
        else:
1494
 
            noise_level = 0
1495
841
        from bzrlib.info import show_bzrdir_info
1496
842
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1497
 
                         verbose=noise_level, outfile=self.outf)
 
843
                         verbose=verbose)
1498
844
 
1499
845
 
1500
846
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.
 
847
    """Make a file unversioned.
 
848
 
 
849
    This makes bzr stop tracking changes to a versioned file.  It does
 
850
    not delete the working copy.
 
851
 
 
852
    You can specify one or more files, and/or --new.  If you specify --new,
 
853
    only 'added' files will be removed.  If you specify both, then new files
 
854
    in the specified directories will be removed.  If the directories are
 
855
    also new, they will also be removed.
1508
856
    """
1509
857
    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']
 
858
    takes_options = ['verbose', Option('new', help='remove newly-added files')]
 
859
    aliases = ['rm']
1522
860
    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)
 
861
    
 
862
    def run(self, file_list, verbose=False, new=False):
 
863
        tree, file_list = tree_files(file_list)
 
864
        if new is False:
 
865
            if file_list is None:
 
866
                raise BzrCommandError('Specify one or more files to remove, or'
 
867
                                      ' use --new.')
 
868
        else:
 
869
            from bzrlib.delta import compare_trees
 
870
            added = [compare_trees(tree.basis_tree(), tree,
 
871
                                   specific_files=file_list).added]
 
872
            file_list = sorted([f[0] for f in added[0]], reverse=True)
1543
873
            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'))
 
874
                raise BzrCommandError('No matching files.')
 
875
        tree.remove(file_list, verbose=verbose, to_file=self.outf)
1558
876
 
1559
877
 
1560
878
class cmd_file_id(Command):
1561
 
    __doc__ = """Print file_id of a particular file or directory.
 
879
    """Print file_id of a particular file or directory.
1562
880
 
1563
881
    The file_id is assigned when the file is first added and remains the
1564
882
    same through all revisions where the file exists, even when it is
1566
884
    """
1567
885
 
1568
886
    hidden = True
1569
 
    _see_also = ['inventory', 'ls']
1570
887
    takes_args = ['filename']
1571
888
 
1572
889
    @display_command
1573
890
    def run(self, filename):
1574
891
        tree, relpath = WorkingTree.open_containing(filename)
1575
 
        i = tree.path2id(relpath)
1576
 
        if i is None:
1577
 
            raise errors.NotVersionedError(filename)
 
892
        i = tree.inventory.path2id(relpath)
 
893
        if i == None:
 
894
            raise BzrError("%r is not a versioned file" % filename)
1578
895
        else:
1579
896
            self.outf.write(i + '\n')
1580
897
 
1581
898
 
1582
899
class cmd_file_path(Command):
1583
 
    __doc__ = """Print path of file_ids to a file or directory.
 
900
    """Print path of file_ids to a file or directory.
1584
901
 
1585
902
    This prints one line for each directory down to the target,
1586
903
    starting at the branch root.
1592
909
    @display_command
1593
910
    def run(self, filename):
1594
911
        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))
 
912
        inv = tree.inventory
 
913
        fid = inv.path2id(relpath)
 
914
        if fid == None:
 
915
            raise BzrError("%r is not a versioned file" % filename)
 
916
        for fip in inv.get_idpath(fid):
 
917
            self.outf.write(fip + '\n')
1602
918
 
1603
919
 
1604
920
class cmd_reconcile(Command):
1605
 
    __doc__ = """Reconcile bzr metadata in a branch.
 
921
    """Reconcile bzr metadata in a branch.
1606
922
 
1607
923
    This can correct data mismatches that may have been caused by
1608
924
    previous ghost operations or bzr upgrades. You should only
1609
 
    need to run this command if 'bzr check' or a bzr developer
 
925
    need to run this command if 'bzr check' or a bzr developer 
1610
926
    advises you to run it.
1611
927
 
1612
928
    If a second branch is provided, cross-branch reconciliation is
1614
930
    id which was not present in very early bzr versions is represented
1615
931
    correctly in both branches.
1616
932
 
1617
 
    At the same time it is run it may recompress data resulting in
 
933
    At the same time it is run it may recompress data resulting in 
1618
934
    a potential saving in disk space or performance gain.
1619
935
 
1620
936
    The branch *MUST* be on a listable system such as local disk or sftp.
1621
937
    """
1622
 
 
1623
 
    _see_also = ['check']
1624
938
    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
939
 
1632
 
    def run(self, branch=".", canonicalize_chks=False):
 
940
    def run(self, branch="."):
1633
941
        from bzrlib.reconcile import reconcile
1634
942
        dir = bzrdir.BzrDir.open(branch)
1635
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
943
        reconcile(dir)
1636
944
 
1637
945
 
1638
946
class cmd_revision_history(Command):
1639
 
    __doc__ = """Display the list of revision ids on a branch."""
1640
 
 
1641
 
    _see_also = ['log']
 
947
    """Display the list of revision ids on a branch."""
1642
948
    takes_args = ['location?']
1643
949
 
1644
950
    hidden = True
1652
958
 
1653
959
 
1654
960
class cmd_ancestry(Command):
1655
 
    __doc__ = """List all revisions merged into this branch."""
1656
 
 
1657
 
    _see_also = ['log', 'revision-history']
 
961
    """List all revisions merged into this branch."""
1658
962
    takes_args = ['location?']
1659
963
 
1660
964
    hidden = True
1671
975
            last_revision = wt.last_revision()
1672
976
 
1673
977
        revision_ids = b.repository.get_ancestry(last_revision)
 
978
        assert revision_ids[0] == None
1674
979
        revision_ids.pop(0)
1675
980
        for revision_id in revision_ids:
1676
981
            self.outf.write(revision_id + '\n')
1677
982
 
1678
983
 
1679
984
class cmd_init(Command):
1680
 
    __doc__ = """Make a directory into a versioned branch.
 
985
    """Make a directory into a versioned branch.
1681
986
 
1682
987
    Use this to create an empty branch, or before importing an
1683
988
    existing project.
1684
989
 
1685
 
    If there is a repository in a parent directory of the location, then
 
990
    If there is a repository in a parent directory of the location, then 
1686
991
    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.
 
992
    init creates a standalone branch which carries its own history in 
 
993
    .bzr.
1689
994
 
1690
995
    If there is already a branch at the location but it has no working tree,
1691
996
    the tree can be populated with 'bzr checkout'.
1692
997
 
1693
 
    Recipe for importing a tree of files::
1694
 
 
 
998
    Recipe for importing a tree of files:
1695
999
        cd ~/project
1696
1000
        bzr init
1697
1001
        bzr add .
1698
1002
        bzr status
1699
 
        bzr commit -m "imported project"
 
1003
        bzr commit -m 'imported project'
1700
1004
    """
1701
 
 
1702
 
    _see_also = ['init-repository', 'branch', 'checkout']
1703
1005
    takes_args = ['location?']
1704
1006
    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):
 
1007
                     Option('format', 
 
1008
                            help='Specify a format for this branch. Current'
 
1009
                                 ' formats are: default, knit, metaweave and'
 
1010
                                 ' weave. Default is knit; metaweave and'
 
1011
                                 ' weave are deprecated',
 
1012
                            type=get_format_type),
 
1013
                     ]
 
1014
    def run(self, location=None, format=None):
1724
1015
        if format is None:
1725
 
            format = bzrdir.format_registry.make_bzrdir('default')
 
1016
            format = get_format_type('default')
1726
1017
        if location is None:
1727
1018
            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:
 
1019
        else:
 
1020
            # The path has to exist to initialize a
 
1021
            # branch inside of it.
 
1022
            # Just using os.mkdir, since I don't
 
1023
            # believe that we want to create a bunch of
 
1024
            # locations if the user supplies an extended path
 
1025
            if not os.path.exists(location):
 
1026
                os.mkdir(location)
 
1027
        try:
 
1028
            existing_bzrdir = bzrdir.BzrDir.open(location)
 
1029
        except NotBranchError:
1750
1030
            # really a NotBzrDir error...
1751
 
            create_branch = bzrdir.BzrDir.create_branch_convenience
1752
 
            if no_tree:
1753
 
                force_new_tree = False
 
1031
            bzrdir.BzrDir.create_branch_convenience(location, format=format)
 
1032
        else:
 
1033
            if existing_bzrdir.has_branch():
 
1034
                if existing_bzrdir.has_workingtree():
 
1035
                    raise errors.AlreadyBranchError(location)
 
1036
                else:
 
1037
                    raise errors.BranchExistsWithoutWorkingTree(location)
1754
1038
            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)
 
1039
                existing_bzrdir.create_branch()
 
1040
                existing_bzrdir.create_workingtree()
1794
1041
 
1795
1042
 
1796
1043
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)
 
1044
    """Create a shared repository to hold branches.
 
1045
 
 
1046
    New branches created under the repository directory will store their revisions
 
1047
    in the repository, not in the branch directory, if the branch format supports
 
1048
    shared storage.
 
1049
 
 
1050
    example:
 
1051
        bzr init-repo repo
 
1052
        bzr init repo/trunk
 
1053
        bzr checkout --lightweight repo/trunk trunk-checkout
 
1054
        cd trunk-checkout
 
1055
        (add files here)
1822
1056
    """
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
 
                    ]
 
1057
    takes_args = ["location"] 
 
1058
    takes_options = [Option('format', 
 
1059
                            help='Specify a format for this repository.'
 
1060
                                 ' Current formats are: default, knit,'
 
1061
                                 ' metaweave and weave. Default is knit;'
 
1062
                                 ' metaweave and weave are deprecated',
 
1063
                            type=get_format_type),
 
1064
                     Option('trees',
 
1065
                             help='Allows branches in repository to have'
 
1066
                             ' a working tree')]
1836
1067
    aliases = ["init-repo"]
1837
 
 
1838
 
    def run(self, location, format=None, no_trees=False):
 
1068
    def run(self, location, format=None, trees=False):
 
1069
        from bzrlib.transport import get_transport
1839
1070
        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)
 
1071
            format = get_format_type('default')
 
1072
        transport = get_transport(location)
 
1073
        if not transport.has('.'):
 
1074
            transport.mkdir('')
 
1075
        newdir = format.initialize_on_transport(transport)
1849
1076
        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)
 
1077
        repo.set_make_working_trees(trees)
1854
1078
 
1855
1079
 
1856
1080
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.
 
1081
    """Show differences in working tree.
 
1082
    
 
1083
    If files are listed, only the changes in those files are listed.
 
1084
    Otherwise, all changes for the tree are listed.
1865
1085
 
1866
1086
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1867
1087
    produces patches suitable for "patch -p1".
1868
1088
 
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
 
1089
    examples:
 
1090
        bzr diff
 
1091
        bzr diff -r1
 
1092
        bzr diff -r1..2
 
1093
        bzr diff --diff-prefix old/:new/
 
1094
        bzr diff bzr.mine bzr.dev
 
1095
        bzr diff foo.c
1941
1096
    """
1942
 
    _see_also = ['status']
 
1097
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
 
1098
    #       or a graphical diff.
 
1099
 
 
1100
    # TODO: Python difflib is not exactly the same as unidiff; should
 
1101
    #       either fix it up or prefer to use an external diff.
 
1102
 
 
1103
    # TODO: Selected-file diff is inefficient and doesn't show you
 
1104
    #       deleted files.
 
1105
 
 
1106
    # TODO: This probably handles non-Unix newlines poorly.
 
1107
    
1943
1108
    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
 
        ]
 
1109
    takes_options = ['revision', 'diff-options', 'prefix']
1970
1110
    aliases = ['di', 'dif']
1971
1111
    encoding_type = 'exact'
1972
1112
 
1973
1113
    @display_command
1974
1114
    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)
 
1115
            prefix=None):
 
1116
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
1978
1117
 
1979
1118
        if (prefix is None) or (prefix == '0'):
1980
1119
            # diff -p0 format
1983
1122
        elif prefix == '1':
1984
1123
            old_label = 'old/'
1985
1124
            new_label = 'new/'
1986
 
        elif ':' in prefix:
 
1125
        else:
 
1126
            if not ':' in prefix:
 
1127
                 raise BzrError("--diff-prefix expects two values separated by a colon")
1987
1128
            old_label, new_label = prefix.split(":")
 
1129
        
 
1130
        try:
 
1131
            tree1, file_list = internal_tree_files(file_list)
 
1132
            tree2 = None
 
1133
            b = None
 
1134
            b2 = None
 
1135
        except FileInWrongBranch:
 
1136
            if len(file_list) != 2:
 
1137
                raise BzrCommandError("Files are in different branches")
 
1138
 
 
1139
            tree1, file1 = WorkingTree.open_containing(file_list[0])
 
1140
            tree2, file2 = WorkingTree.open_containing(file_list[1])
 
1141
            if file1 != "" or file2 != "":
 
1142
                # FIXME diff those two files. rbc 20051123
 
1143
                raise BzrCommandError("Files are in different branches")
 
1144
            file_list = None
 
1145
        except NotBranchError:
 
1146
            # Don't raise an error when bzr diff is called from
 
1147
            # outside a working tree.
 
1148
            tree1, tree2 = None, None
 
1149
        if revision is not None:
 
1150
            if tree2 is not None:
 
1151
                raise BzrCommandError("Can't specify -r with two branches")
 
1152
            if (len(revision) == 1) or (revision[1].spec is None):
 
1153
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1154
                                       revision[0], 
 
1155
                                       old_label=old_label, new_label=new_label)
 
1156
            elif len(revision) == 2:
 
1157
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1158
                                       revision[0], revision[1],
 
1159
                                       old_label=old_label, new_label=new_label)
 
1160
            else:
 
1161
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
1988
1162
        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)
 
1163
            if tree2 is not None:
 
1164
                return show_diff_trees(tree1, tree2, sys.stdout, 
 
1165
                                       specific_files=file_list,
 
1166
                                       external_diff_options=diff_options,
 
1167
                                       old_label=old_label, new_label=new_label)
 
1168
            else:
 
1169
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1170
                                       old_label=old_label, new_label=new_label)
2015
1171
 
2016
1172
 
2017
1173
class cmd_deleted(Command):
2018
 
    __doc__ = """List files deleted in the working tree.
 
1174
    """List files deleted in the working tree.
2019
1175
    """
2020
1176
    # TODO: Show files deleted since a previous revision, or
2021
1177
    # between two revisions.
2023
1179
    # directories with readdir, rather than stating each one.  Same
2024
1180
    # level of effort but possibly much less IO.  (Or possibly not,
2025
1181
    # if the directories are very large...)
2026
 
    _see_also = ['status', 'ls']
2027
 
    takes_options = ['directory', 'show-ids']
 
1182
    takes_options = ['show-ids']
2028
1183
 
2029
1184
    @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)
 
1185
    def run(self, show_ids=False):
 
1186
        tree = WorkingTree.open_containing(u'.')[0]
2033
1187
        old = tree.basis_tree()
2034
 
        self.add_cleanup(old.lock_read().unlock)
2035
1188
        for path, ie in old.inventory.iter_entries():
2036
1189
            if not tree.has_id(ie.file_id):
2037
1190
                self.outf.write(path)
2042
1195
 
2043
1196
 
2044
1197
class cmd_modified(Command):
2045
 
    __doc__ = """List files modified in working tree.
2046
 
    """
2047
 
 
 
1198
    """List files modified in working tree."""
2048
1199
    hidden = True
2049
 
    _see_also = ['status', 'ls']
2050
 
    takes_options = ['directory', 'null']
2051
 
 
2052
1200
    @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())
 
1201
    def run(self):
 
1202
        from bzrlib.delta import compare_trees
 
1203
 
 
1204
        tree = WorkingTree.open_containing(u'.')[0]
 
1205
        td = compare_trees(tree.basis_tree(), tree)
 
1206
 
2056
1207
        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')
 
1208
            self.outf.write(path + '\n')
2061
1209
 
2062
1210
 
2063
1211
class cmd_added(Command):
2064
 
    __doc__ = """List files added in working tree.
2065
 
    """
2066
 
 
 
1212
    """List files added in working tree."""
2067
1213
    hidden = True
2068
 
    _see_also = ['status', 'ls']
2069
 
    takes_options = ['directory', 'null']
2070
 
 
2071
1214
    @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
 
1215
    def run(self):
 
1216
        wt = WorkingTree.open_containing(u'.')[0]
 
1217
        basis_inv = wt.basis_tree().inventory
2078
1218
        inv = wt.inventory
2079
1219
        for file_id in inv:
2080
1220
            if file_id in basis_inv:
2081
1221
                continue
2082
 
            if inv.is_root(file_id) and len(basis_inv) == 0:
2083
 
                continue
2084
1222
            path = inv.id2path(file_id)
2085
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
 
1223
            if not os.access(osutils.abspath(path), os.F_OK):
2086
1224
                continue
2087
 
            if null:
2088
 
                self.outf.write(path + '\0')
2089
 
            else:
2090
 
                self.outf.write(osutils.quotefn(path) + '\n')
 
1225
            self.outf.write(path + '\n')
2091
1226
 
2092
1227
 
2093
1228
class cmd_root(Command):
2094
 
    __doc__ = """Show the tree root directory.
 
1229
    """Show the tree root directory.
2095
1230
 
2096
1231
    The root is the nearest enclosing directory with a .bzr control
2097
1232
    directory."""
2098
 
 
2099
1233
    takes_args = ['filename?']
2100
1234
    @display_command
2101
1235
    def run(self, filename=None):
2104
1238
        self.outf.write(tree.basedir + '\n')
2105
1239
 
2106
1240
 
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
1241
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.
 
1242
    """Show log of a branch, file, or directory.
 
1243
 
 
1244
    By default show the log of the branch containing the working directory.
 
1245
 
 
1246
    To request a range of logs, you can use the command -r begin..end
 
1247
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
1248
    also valid.
 
1249
 
 
1250
    examples:
 
1251
        bzr log
 
1252
        bzr log foo.c
 
1253
        bzr log -r -10.. http://server/branch
2274
1254
    """
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
 
            ]
 
1255
 
 
1256
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
1257
 
 
1258
    takes_args = ['location?']
 
1259
    takes_options = [Option('forward', 
 
1260
                            help='show from oldest to newest'),
 
1261
                     'timezone', 
 
1262
                     Option('verbose', 
 
1263
                             help='show files changed in each revision'),
 
1264
                     'show-ids', 'revision',
 
1265
                     'log-format',
 
1266
                     'line', 'long', 
 
1267
                     Option('message',
 
1268
                            help='show revisions whose message matches this regexp',
 
1269
                            type=str),
 
1270
                     'short',
 
1271
                     ]
2321
1272
    encoding_type = 'replace'
2322
1273
 
2323
1274
    @display_command
2324
 
    def run(self, file_list=None, timezone='original',
 
1275
    def run(self, location=None, timezone='original',
2325
1276
            verbose=False,
2326
1277
            show_ids=False,
2327
1278
            forward=False,
2328
1279
            revision=None,
2329
 
            change=None,
2330
1280
            log_format=None,
2331
 
            levels=None,
2332
1281
            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
 
            )
 
1282
            long=False,
 
1283
            short=False,
 
1284
            line=False):
 
1285
        from bzrlib.log import log_formatter, show_log
 
1286
        assert message is None or isinstance(message, basestring), \
 
1287
            "invalid message argument %r" % message
2344
1288
        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
 
1289
        
 
1290
        # log everything
 
1291
        file_id = None
 
1292
        if location:
 
1293
            # find the file id to log:
 
1294
 
 
1295
            dir, fp = bzrdir.BzrDir.open_containing(location)
 
1296
            b = dir.open_branch()
 
1297
            if fp != '':
 
1298
                try:
 
1299
                    # might be a tree:
 
1300
                    inv = dir.open_workingtree().inventory
 
1301
                except (errors.NotBranchError, errors.NotLocalUrl):
 
1302
                    # either no tree, or is remote.
 
1303
                    inv = b.basis_tree().inventory
 
1304
                file_id = inv.path2id(fp)
 
1305
        else:
 
1306
            # local dir only
 
1307
            # FIXME ? log the current subdir only RBC 20060203 
 
1308
            dir, relpath = bzrdir.BzrDir.open_containing('.')
 
1309
            b = dir.open_branch()
 
1310
 
 
1311
        if revision is None:
 
1312
            rev1 = None
 
1313
            rev2 = None
 
1314
        elif len(revision) == 1:
 
1315
            rev1 = rev2 = revision[0].in_history(b).revno
 
1316
        elif len(revision) == 2:
 
1317
            if revision[0].spec is None:
 
1318
                # missing begin-range means first revision
 
1319
                rev1 = 1
 
1320
            else:
 
1321
                rev1 = revision[0].in_history(b).revno
 
1322
 
 
1323
            if revision[1].spec is None:
 
1324
                # missing end-range means last known revision
 
1325
                rev2 = b.revno()
 
1326
            else:
 
1327
                rev2 = revision[1].in_history(b).revno
 
1328
        else:
 
1329
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
1330
 
 
1331
        # By this point, the revision numbers are converted to the +ve
 
1332
        # form if they were supplied in the -ve form, so we can do
 
1333
        # this comparison in relative safety
 
1334
        if rev1 > rev2:
 
1335
            (rev2, rev1) = (rev1, rev2)
 
1336
 
 
1337
        if (log_format == None):
 
1338
            default = b.get_config().log_format()
 
1339
            log_format = get_log_format(long=long, short=short, line=line, 
 
1340
                                        default=default)
 
1341
        lf = log_formatter(log_format,
 
1342
                           show_ids=show_ids,
 
1343
                           to_file=self.outf,
 
1344
                           show_timezone=timezone)
 
1345
 
 
1346
        show_log(b,
 
1347
                 lf,
 
1348
                 file_id,
 
1349
                 verbose=verbose,
 
1350
                 direction=direction,
 
1351
                 start_revision=rev1,
 
1352
                 end_revision=rev2,
 
1353
                 search=message)
 
1354
 
2499
1355
 
2500
1356
def get_log_format(long=False, short=False, line=False, default='long'):
2501
1357
    log_format = default
2509
1365
 
2510
1366
 
2511
1367
class cmd_touching_revisions(Command):
2512
 
    __doc__ = """Return revision-ids which affected a particular file.
 
1368
    """Return revision-ids which affected a particular file.
2513
1369
 
2514
1370
    A more user-friendly interface is "bzr log FILE".
2515
1371
    """
2520
1376
    @display_command
2521
1377
    def run(self, filename):
2522
1378
        tree, relpath = WorkingTree.open_containing(filename)
2523
 
        file_id = tree.path2id(relpath)
2524
1379
        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:
 
1380
        inv = tree.read_working_inventory()
 
1381
        file_id = inv.path2id(relpath)
 
1382
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
2528
1383
            self.outf.write("%6d %s\n" % (revno, what))
2529
1384
 
2530
1385
 
2531
1386
class cmd_ls(Command):
2532
 
    __doc__ = """List files in a tree.
 
1387
    """List files in a tree.
2533
1388
    """
 
1389
    # TODO: Take a revision or remote path and list that tree instead.
 
1390
    hidden = True
 
1391
    takes_options = ['verbose', 'revision',
 
1392
                     Option('non-recursive',
 
1393
                            help='don\'t recurse into sub-directories'),
 
1394
                     Option('from-root',
 
1395
                            help='Print all paths from the root of the branch.'),
 
1396
                     Option('unknown', help='Print unknown files'),
 
1397
                     Option('versioned', help='Print versioned files'),
 
1398
                     Option('ignored', help='Print ignored files'),
2534
1399
 
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
 
            ]
 
1400
                     Option('null', help='Null separate the files'),
 
1401
                    ]
2557
1402
    @display_command
2558
 
    def run(self, revision=None, verbose=False,
2559
 
            recursive=False, from_root=False,
 
1403
    def run(self, revision=None, verbose=False, 
 
1404
            non_recursive=False, from_root=False,
2560
1405
            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')
 
1406
            null=False):
2565
1407
 
2566
1408
        if verbose and null:
2567
 
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
 
1409
            raise BzrCommandError('Cannot set both --verbose and --null')
2568
1410
        all = not (unknown or versioned or ignored)
2569
1411
 
2570
1412
        selection = {'I':ignored, '?':unknown, 'V':versioned}
2571
1413
 
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
 
1414
        tree, relpath = WorkingTree.open_containing(u'.')
2584
1415
        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))
 
1416
            relpath = u''
 
1417
        elif relpath:
 
1418
            relpath += '/'
 
1419
        if revision is not None:
 
1420
            tree = tree.branch.repository.revision_tree(
 
1421
                revision[0].in_history(tree.branch).rev_id)
 
1422
 
 
1423
        for fp, fc, kind, fid, entry in tree.list_files():
 
1424
            if fp.startswith(relpath):
 
1425
                fp = fp[len(relpath):]
 
1426
                if non_recursive and '/' in fp:
 
1427
                    continue
 
1428
                if not all and not selection[fc]:
 
1429
                    continue
 
1430
                if verbose:
 
1431
                    kindch = entry.kind_character()
 
1432
                    self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
 
1433
                elif null:
 
1434
                    self.outf.write(fp + '\0')
 
1435
                    self.outf.flush()
2644
1436
                else:
2645
 
                    self.outf.write(outstring + '\n')
 
1437
                    self.outf.write(fp + '\n')
2646
1438
 
2647
1439
 
2648
1440
class cmd_unknowns(Command):
2649
 
    __doc__ = """List unknown files.
2650
 
    """
2651
 
 
2652
 
    hidden = True
2653
 
    _see_also = ['ls']
2654
 
    takes_options = ['directory']
2655
 
 
 
1441
    """List unknown files."""
2656
1442
    @display_command
2657
 
    def run(self, directory=u'.'):
2658
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
1443
    def run(self):
 
1444
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
2659
1445
            self.outf.write(osutils.quotefn(f) + '\n')
2660
1446
 
2661
1447
 
2662
1448
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.
 
1449
    """Ignore a command or pattern.
2672
1450
 
2673
1451
    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 "!!*~"
 
1452
 
 
1453
    If the pattern contains a slash, it is compared to the whole path
 
1454
    from the branch root.  Otherwise, it is compared to only the last
 
1455
    component of the path.  To match a file only in the root directory,
 
1456
    prepend './'.
 
1457
 
 
1458
    Ignore patterns are case-insensitive on case-insensitive systems.
 
1459
 
 
1460
    Note: wildcards must be quoted from the shell on Unix.
 
1461
 
 
1462
    examples:
 
1463
        bzr ignore ./Makefile
 
1464
        bzr ignore '*.class'
2734
1465
    """
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)
 
1466
    # TODO: Complain if the filename is absolute
 
1467
    takes_args = ['name_pattern?']
 
1468
    takes_options = [
 
1469
                     Option('old-default-rules',
 
1470
                            help='Out the ignore rules bzr < 0.9 always used.')
 
1471
                     ]
 
1472
    
 
1473
    def run(self, name_pattern=None, old_default_rules=None):
 
1474
        from bzrlib.atomicfile import AtomicFile
 
1475
        if old_default_rules is not None:
 
1476
            # dump the rules and exit
 
1477
            for pattern in bzrlib.DEFAULT_IGNORE:
 
1478
                print pattern
2750
1479
            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),))
 
1480
        if name_pattern is None:
 
1481
            raise BzrCommandError("ignore requires a NAME_PATTERN")
 
1482
        tree, relpath = WorkingTree.open_containing(u'.')
 
1483
        ifn = tree.abspath('.bzrignore')
 
1484
        if os.path.exists(ifn):
 
1485
            f = open(ifn, 'rt')
 
1486
            try:
 
1487
                igns = f.read().decode('utf-8')
 
1488
            finally:
 
1489
                f.close()
 
1490
        else:
 
1491
            igns = ''
 
1492
 
 
1493
        # TODO: If the file already uses crlf-style termination, maybe
 
1494
        # we should use that for the newly added lines?
 
1495
 
 
1496
        if igns and igns[-1] != '\n':
 
1497
            igns += '\n'
 
1498
        igns += name_pattern + '\n'
 
1499
 
 
1500
        f = AtomicFile(ifn, 'wt')
 
1501
        try:
 
1502
            f.write(igns.encode('utf-8'))
 
1503
            f.commit()
 
1504
        finally:
 
1505
            f.close()
 
1506
 
 
1507
        inv = tree.inventory
 
1508
        if inv.path2id('.bzrignore'):
 
1509
            mutter('.bzrignore is already versioned')
 
1510
        else:
 
1511
            mutter('need to make new .bzrignore file versioned')
 
1512
            tree.add(['.bzrignore'])
2785
1513
 
2786
1514
 
2787
1515
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
 
 
 
1516
    """List ignored files and the patterns that matched them.
 
1517
 
 
1518
    See also: bzr ignore"""
2802
1519
    @display_command
2803
 
    def run(self, directory=u'.'):
2804
 
        tree = WorkingTree.open_containing(directory)[0]
2805
 
        self.add_cleanup(tree.lock_read().unlock)
 
1520
    def run(self):
 
1521
        tree = WorkingTree.open_containing(u'.')[0]
2806
1522
        for path, file_class, kind, file_id, entry in tree.list_files():
2807
1523
            if file_class != 'I':
2808
1524
                continue
2809
1525
            ## XXX: Slightly inefficient since this was already calculated
2810
1526
            pat = tree.is_ignored(path)
2811
 
            self.outf.write('%-50s %s\n' % (path, pat))
 
1527
            print '%-50s %s' % (path, pat)
2812
1528
 
2813
1529
 
2814
1530
class cmd_lookup_revision(Command):
2815
 
    __doc__ = """Lookup the revision-id from a revision-number
 
1531
    """Lookup the revision-id from a revision-number
2816
1532
 
2817
 
    :Examples:
 
1533
    example:
2818
1534
        bzr lookup-revision 33
2819
1535
    """
2820
1536
    hidden = True
2821
1537
    takes_args = ['revno']
2822
 
    takes_options = ['directory']
2823
 
 
 
1538
    
2824
1539
    @display_command
2825
 
    def run(self, revno, directory=u'.'):
 
1540
    def run(self, revno):
2826
1541
        try:
2827
1542
            revno = int(revno)
2828
1543
        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)
 
1544
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
1545
 
 
1546
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2833
1547
 
2834
1548
 
2835
1549
class cmd_export(Command):
2836
 
    __doc__ = """Export current or past revision to a destination directory or archive.
 
1550
    """Export past revision to destination directory.
2837
1551
 
2838
1552
    If no revision is specified this exports the last committed revision.
2839
1553
 
2841
1555
    given, try to find the format with the extension. If no extension
2842
1556
    is found exports to a directory (equivalent to --format=dir).
2843
1557
 
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)
 
1558
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1559
    is given, the top directory will be the root name of the file.
 
1560
 
 
1561
    Note: export of tree with non-ascii filenames to zip is not supported.
 
1562
 
 
1563
     Supported formats       Autodetected by extension
 
1564
     -----------------       -------------------------
 
1565
         dir                            -
2857
1566
         tar                          .tar
2858
1567
         tbz2                    .tar.bz2, .tbz2
2859
1568
         tgz                      .tar.gz, .tgz
2860
1569
         zip                          .zip
2861
 
      =================       =========================
2862
1570
    """
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'.'):
 
1571
    takes_args = ['dest']
 
1572
    takes_options = ['revision', 'format', 'root']
 
1573
    def run(self, dest, revision=None, format=None, root=None):
2880
1574
        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
 
1575
        tree = WorkingTree.open_containing(u'.')[0]
 
1576
        b = tree.branch
 
1577
        if revision is None:
 
1578
            # should be tree.last_revision  FIXME
 
1579
            rev_id = b.last_revision()
2886
1580
        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)
 
1581
            if len(revision) != 1:
 
1582
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
1583
            rev_id = revision[0].in_history(b).rev_id
 
1584
        t = b.repository.revision_tree(rev_id)
2891
1585
        try:
2892
 
            export(rev_tree, dest, format, root, subdir, filtered=filters,
2893
 
                   per_file_timestamps=per_file_timestamps)
 
1586
            export(t, dest, format, root)
2894
1587
        except errors.NoSuchExportFormat, e:
2895
 
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
 
1588
            raise BzrCommandError('Unsupported export format: %s' % e.format)
2896
1589
 
2897
1590
 
2898
1591
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
 
        ]
 
1592
    """Write a file's text from a previous revision."""
 
1593
 
 
1594
    takes_options = ['revision']
2914
1595
    takes_args = ['filename']
2915
 
    encoding_type = 'exact'
2916
1596
 
2917
1597
    @display_command
2918
 
    def run(self, filename, revision=None, name_from_revision=False,
2919
 
            filters=False, directory=None):
 
1598
    def run(self, filename, revision=None):
2920
1599
        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)
 
1600
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
1601
        tree = None
 
1602
        try:
 
1603
            tree, relpath = WorkingTree.open_containing(filename)
 
1604
            b = tree.branch
 
1605
        except NotBranchError:
 
1606
            pass
2928
1607
 
2929
 
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2930
 
        filtered):
2931
1608
        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)
 
1609
            b, relpath = Branch.open_containing(filename)
 
1610
        if revision is None:
 
1611
            revision_id = b.last_revision()
 
1612
        else:
 
1613
            revision_id = revision[0].in_history(b).rev_id
 
1614
        b.print_file(relpath, revision_id)
2980
1615
 
2981
1616
 
2982
1617
class cmd_local_time_offset(Command):
2983
 
    __doc__ = """Show the offset in seconds from GMT to local time."""
2984
 
    hidden = True
 
1618
    """Show the offset in seconds from GMT to local time."""
 
1619
    hidden = True    
2985
1620
    @display_command
2986
1621
    def run(self):
2987
 
        self.outf.write("%s\n" % osutils.local_time_offset())
 
1622
        print osutils.local_time_offset()
2988
1623
 
2989
1624
 
2990
1625
 
2991
1626
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.)
 
1627
    """Commit changes into a new revision.
 
1628
    
 
1629
    If no arguments are given, the entire tree is committed.
 
1630
 
 
1631
    If selected files are specified, only changes to those files are
 
1632
    committed.  If a directory is specified then the directory and everything 
 
1633
    within it is committed.
 
1634
 
 
1635
    A selected-file commit may fail in some cases where the committed
 
1636
    tree would be invalid, such as trying to commit a file in a
 
1637
    newly-added directory that is not itself committed.
3063
1638
    """
3064
1639
    # TODO: Run hooks on tree to-be-committed, and after commit.
3065
1640
 
3070
1645
 
3071
1646
    # XXX: verbose currently does nothing
3072
1647
 
3073
 
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
3074
1648
    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
 
             ]
 
1649
    takes_options = ['message', 'verbose', 
 
1650
                     Option('unchanged',
 
1651
                            help='commit even if nothing has changed'),
 
1652
                     Option('file', type=str, 
 
1653
                            argname='msgfile',
 
1654
                            help='file containing commit message'),
 
1655
                     Option('strict',
 
1656
                            help="refuse to commit if there are unknown "
 
1657
                            "files in the working tree."),
 
1658
                     Option('local',
 
1659
                            help="perform a local only commit in a bound "
 
1660
                                 "branch. Such commits are not pushed to "
 
1661
                                 "the master branch until a normal commit "
 
1662
                                 "is performed."
 
1663
                            ),
 
1664
                     ]
3110
1665
    aliases = ['ci', 'checkin']
3111
1666
 
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))
 
1667
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1668
            unchanged=False, strict=False, local=False):
 
1669
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
 
1670
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
 
1671
                StrictCommitFailed)
 
1672
        from bzrlib.msgeditor import edit_commit_message, \
 
1673
                make_commit_message_template
 
1674
        from tempfile import TemporaryFile
3152
1675
 
3153
1676
        # TODO: Need a blackbox test for invoking the external editor; may be
3154
1677
        # slightly problematic to run this cross-platform.
3155
1678
 
3156
 
        # TODO: do more checks that the commit will succeed before
 
1679
        # TODO: do more checks that the commit will succeed before 
3157
1680
        # spending the user's valuable time typing a commit message.
3158
 
 
3159
 
        properties = {}
3160
 
 
3161
 
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
1681
        #
 
1682
        # TODO: if the commit *does* happen to fail, then save the commit 
 
1683
        # message to a temporary file where it can be recovered
 
1684
        tree, selected_list = tree_files(selected_list)
3162
1685
        if selected_list == ['']:
3163
1686
            # workaround - commit of root of tree should be exactly the same
3164
1687
            # as just default commit in that tree, and succeed even though
3165
1688
            # selected-file merge commit is not done yet
3166
1689
            selected_list = []
3167
1690
 
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
1691
        if local and not tree.branch.get_bound_location():
3176
1692
            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
 
1693
        if message is None and not file:
 
1694
            template = make_commit_message_template(tree, selected_list)
 
1695
            message = edit_commit_message(template)
 
1696
            if message is None:
 
1697
                raise BzrCommandError("please specify a commit message"
 
1698
                                      " with either --message or --file")
 
1699
        elif message and file:
 
1700
            raise BzrCommandError("please specify either --message or --file")
 
1701
        
 
1702
        if file:
 
1703
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
1704
 
 
1705
        if message == "":
 
1706
            raise BzrCommandError("empty commit message specified")
 
1707
        
 
1708
        if verbose:
 
1709
            reporter = ReportCommitToLog()
 
1710
        else:
 
1711
            reporter = NullCommitReporter()
 
1712
        
3234
1713
        try:
3235
 
            tree.commit(message_callback=get_message,
3236
 
                        specific_files=selected_list,
 
1714
            tree.commit(message, specific_files=selected_list,
3237
1715
                        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))
 
1716
                        reporter=reporter)
3242
1717
        except PointlessCommit:
3243
 
            raise errors.BzrCommandError("No changes to commit."
3244
 
                              " Use --unchanged to commit anyhow.")
 
1718
            # FIXME: This should really happen before the file is read in;
 
1719
            # perhaps prepare the commit; get the message; then actually commit
 
1720
            raise BzrCommandError("no changes to commit."
 
1721
                                  " use --unchanged to commit anyhow")
3245
1722
        except ConflictsInTree:
3246
 
            raise errors.BzrCommandError('Conflicts detected in working '
3247
 
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3248
 
                ' resolve.')
 
1723
            raise BzrCommandError("Conflicts detected in working tree.  "
 
1724
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
3249
1725
        except StrictCommitFailed:
3250
 
            raise errors.BzrCommandError("Commit refused because there are"
3251
 
                              " unknown files in the working tree.")
 
1726
            raise BzrCommandError("Commit refused because there are unknown "
 
1727
                                  "files in the working tree.")
3252
1728
        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
 
1729
            raise BzrCommandError(str(e)
 
1730
                                  + ' Either unbind, update, or'
 
1731
                                    ' pass --local to commit.')
3258
1732
 
3259
1733
 
3260
1734
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
 
1735
    """Validate consistency of branch history.
 
1736
 
 
1737
    This command checks various invariants about the branch storage to
 
1738
    detect data corruption or bzr bugs.
3308
1739
    """
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)
 
1740
    takes_args = ['branch?']
 
1741
    takes_options = ['verbose']
 
1742
 
 
1743
    def run(self, branch=None, verbose=False):
 
1744
        from bzrlib.check import check
 
1745
        if branch is None:
 
1746
            tree = WorkingTree.open_containing()[0]
 
1747
            branch = tree.branch
 
1748
        else:
 
1749
            branch = Branch.open(branch)
 
1750
        check(branch, verbose)
 
1751
 
 
1752
 
 
1753
class cmd_scan_cache(Command):
 
1754
    hidden = True
 
1755
    def run(self):
 
1756
        from bzrlib.hashcache import HashCache
 
1757
 
 
1758
        c = HashCache(u'.')
 
1759
        c.read()
 
1760
        c.scan()
 
1761
            
 
1762
        print '%6d stats' % c.stat_count
 
1763
        print '%6d in hashcache' % len(c._cache)
 
1764
        print '%6d files removed from cache' % c.removed_count
 
1765
        print '%6d hashes updated' % c.update_count
 
1766
        print '%6d files changed too recently to cache' % c.danger_count
 
1767
 
 
1768
        if c.needs_write:
 
1769
            c.write()
3328
1770
 
3329
1771
 
3330
1772
class cmd_upgrade(Command):
3331
 
    __doc__ = """Upgrade branch storage to current format.
 
1773
    """Upgrade branch storage to current format.
3332
1774
 
3333
1775
    The check command or bzr developers may sometimes advise you to run
3334
1776
    this command. When the default format has changed you may also be warned
3335
1777
    during other operations to upgrade.
3336
1778
    """
3337
 
 
3338
 
    _see_also = ['check']
3339
1779
    takes_args = ['url?']
3340
1780
    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'),
 
1781
                     Option('format', 
 
1782
                            help='Upgrade to a specific format. Current formats'
 
1783
                                 ' are: default, knit, metaweave and weave.'
 
1784
                                 ' Default is knit; metaweave and weave are'
 
1785
                                 ' deprecated',
 
1786
                            type=get_format_type),
3347
1787
                    ]
3348
1788
 
 
1789
 
3349
1790
    def run(self, url='.', format=None):
3350
1791
        from bzrlib.upgrade import upgrade
 
1792
        if format is None:
 
1793
            format = get_format_type('default')
3351
1794
        upgrade(url, format)
3352
1795
 
3353
1796
 
3354
1797
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>"
 
1798
    """Show or set bzr user id.
 
1799
    
 
1800
    examples:
 
1801
        bzr whoami --email
 
1802
        bzr whoami 'Frank Chu <fchu@example.com>'
3365
1803
    """
3366
 
    takes_options = [ 'directory',
3367
 
                      Option('email',
3368
 
                             help='Display email address only.'),
 
1804
    takes_options = [ Option('email',
 
1805
                             help='display email address only'),
3369
1806
                      Option('branch',
3370
 
                             help='Set identity for the current branch instead of '
3371
 
                                  'globally.'),
 
1807
                             help='set identity for the current branch instead of '
 
1808
                                  'globally'),
3372
1809
                    ]
3373
1810
    takes_args = ['name?']
3374
1811
    encoding_type = 'replace'
3375
 
 
 
1812
    
3376
1813
    @display_command
3377
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
1814
    def run(self, email=False, branch=False, name=None):
3378
1815
        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()
 
1816
            # use branch if we're inside one; otherwise global config
 
1817
            try:
 
1818
                c = Branch.open_containing('.')[0].get_config()
 
1819
            except NotBranchError:
 
1820
                c = config.GlobalConfig()
3387
1821
            if email:
3388
1822
                self.outf.write(c.user_email() + '\n')
3389
1823
            else:
3390
1824
                self.outf.write(c.username() + '\n')
3391
1825
            return
3392
1826
 
3393
 
        # display a warning if an email address isn't included in the given name.
3394
 
        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
1827
        # use global config unless --branch given
3401
1828
        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()
 
1829
            c = Branch.open_containing('.')[0].get_config()
3406
1830
        else:
3407
 
            c = _mod_config.GlobalConfig()
 
1831
            c = config.GlobalConfig()
3408
1832
        c.set_user_option('email', name)
3409
1833
 
3410
1834
 
3411
1835
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.
 
1836
    """Print or set the branch nickname.  
 
1837
 
 
1838
    If unset, the tree root directory name is used as the nickname
 
1839
    To print the current nickname, execute with no argument.  
3419
1840
    """
3420
 
 
3421
 
    _see_also = ['info']
3422
1841
    takes_args = ['nickname?']
3423
 
    takes_options = ['directory']
3424
 
    def run(self, nickname=None, directory=u'.'):
3425
 
        branch = Branch.open_containing(directory)[0]
 
1842
    def run(self, nickname=None):
 
1843
        branch = Branch.open_containing(u'.')[0]
3426
1844
        if nickname is None:
3427
1845
            self.printme(branch)
3428
1846
        else:
3430
1848
 
3431
1849
    @display_command
3432
1850
    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)
 
1851
        print branch.nick 
3504
1852
 
3505
1853
 
3506
1854
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.
 
1855
    """Run internal test suite.
 
1856
    
 
1857
    This creates temporary test directories in the working directory,
 
1858
    but not existing data is affected.  These directories are deleted
 
1859
    if the tests pass, or left behind to help in debugging if they
 
1860
    fail and --keep-output is specified.
 
1861
    
 
1862
    If arguments are given, they are regular expressions that say
 
1863
    which tests should run.
3531
1864
 
3532
1865
    If the global option '--no-plugins' is given, plugins are not loaded
3533
1866
    before running the selftests.  This has two effects: features provided or
3534
1867
    modified by plugins will not be tested, and tests provided by plugins will
3535
1868
    not be run.
3536
1869
 
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
 
1870
    examples:
 
1871
        bzr selftest ignore
 
1872
        bzr --no-plugins selftest -v
3554
1873
    """
 
1874
    # TODO: --list should give a list of all available tests
 
1875
 
3555
1876
    # NB: this is used from the class without creating an instance, which is
3556
1877
    # why it does not have a self parameter.
3557
1878
    def get_transport_type(typestring):
3558
1879
        """Parse and return a transport specifier."""
3559
1880
        if typestring == "sftp":
3560
 
            from bzrlib.tests import stub_sftp
3561
 
            return stub_sftp.SFTPAbsoluteServer
 
1881
            from bzrlib.transport.sftp import SFTPAbsoluteServer
 
1882
            return SFTPAbsoluteServer
3562
1883
        if typestring == "memory":
3563
 
            from bzrlib.tests import test_server
3564
 
            return memory.MemoryServer
 
1884
            from bzrlib.transport.memory import MemoryServer
 
1885
            return MemoryServer
3565
1886
        if typestring == "fakenfs":
3566
 
            from bzrlib.tests import test_server
3567
 
            return test_server.FakeNFSServer
 
1887
            from bzrlib.transport.fakenfs import FakeNFSServer
 
1888
            return FakeNFSServer
3568
1889
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3569
1890
            (typestring)
3570
 
        raise errors.BzrCommandError(msg)
 
1891
        raise BzrCommandError(msg)
3571
1892
 
3572
1893
    hidden = True
3573
1894
    takes_args = ['testspecs*']
3574
1895
    takes_options = ['verbose',
3575
 
                     Option('one',
3576
 
                             help='Stop when one test fails.',
3577
 
                             short_name='1',
3578
 
                             ),
3579
 
                     Option('transport',
 
1896
                     Option('one', help='stop when one test fails'),
 
1897
                     Option('keep-output', 
 
1898
                            help='keep output directories when tests fail'),
 
1899
                     Option('transport', 
3580
1900
                            help='Use a different transport by default '
3581
1901
                                 'throughout the test suite.',
3582
1902
                            type=get_transport_type),
3583
 
                     Option('benchmark',
3584
 
                            help='Run the benchmarks rather than selftests.',
3585
 
                            hidden=True),
 
1903
                     Option('benchmark', help='run the bzr bencharks.'),
3586
1904
                     Option('lsprof-timed',
3587
 
                            help='Generate lsprof output for benchmarked'
 
1905
                            help='generate lsprof output for benchmarked'
3588
1906
                                 ' 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
1907
                     ]
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)
 
1908
 
 
1909
    def run(self, testspecs_list=None, verbose=None, one=False,
 
1910
            keep_output=False, transport=None, benchmark=None,
 
1911
            lsprof_timed=None):
 
1912
        import bzrlib.ui
 
1913
        from bzrlib.tests import selftest
 
1914
        import bzrlib.benchmarks as benchmarks
 
1915
        # we don't want progress meters from the tests to go to the
 
1916
        # real output; and we don't want log messages cluttering up
 
1917
        # the real logs.
 
1918
        save_ui = ui.ui_factory
 
1919
        print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
 
1920
        print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
 
1921
        print
 
1922
        info('running tests...')
3686
1923
        try:
3687
 
            result = tests.selftest(**selftest_kwargs)
 
1924
            ui.ui_factory = ui.SilentUIFactory()
 
1925
            if testspecs_list is not None:
 
1926
                pattern = '|'.join(testspecs_list)
 
1927
            else:
 
1928
                pattern = ".*"
 
1929
            if benchmark:
 
1930
                test_suite_factory = benchmarks.test_suite
 
1931
                if verbose is None:
 
1932
                    verbose = True
 
1933
            else:
 
1934
                test_suite_factory = None
 
1935
                if verbose is None:
 
1936
                    verbose = False
 
1937
            result = selftest(verbose=verbose, 
 
1938
                              pattern=pattern,
 
1939
                              stop_on_failure=one, 
 
1940
                              keep_output=keep_output,
 
1941
                              transport=transport,
 
1942
                              test_suite_factory=test_suite_factory,
 
1943
                              lsprof_timed=lsprof_timed)
 
1944
            if result:
 
1945
                info('tests passed')
 
1946
            else:
 
1947
                info('tests failed')
 
1948
            return int(not result)
3688
1949
        finally:
3689
 
            cleanup()
3690
 
        return int(not result)
 
1950
            ui.ui_factory = save_ui
 
1951
 
 
1952
 
 
1953
def _get_bzr_branch():
 
1954
    """If bzr is run from a branch, return Branch or None"""
 
1955
    from os.path import dirname
 
1956
    
 
1957
    try:
 
1958
        branch = Branch.open(dirname(osutils.abspath(dirname(__file__))))
 
1959
        return branch
 
1960
    except errors.BzrError:
 
1961
        return None
 
1962
    
 
1963
 
 
1964
def show_version():
 
1965
    import bzrlib
 
1966
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1967
    # is bzrlib itself in a branch?
 
1968
    branch = _get_bzr_branch()
 
1969
    if branch:
 
1970
        rh = branch.revision_history()
 
1971
        revno = len(rh)
 
1972
        print "  bzr checkout, revision %d" % (revno,)
 
1973
        print "  nick: %s" % (branch.nick,)
 
1974
        if rh:
 
1975
            print "  revid: %s" % (rh[-1],)
 
1976
    print "Using python interpreter:", sys.executable
 
1977
    import site
 
1978
    print "Using python standard library:", os.path.dirname(site.__file__)
 
1979
    print "Using bzrlib:",
 
1980
    if len(bzrlib.__path__) > 1:
 
1981
        # print repr, which is a good enough way of making it clear it's
 
1982
        # more than one element (eg ['/foo/bar', '/foo/bzr'])
 
1983
        print repr(bzrlib.__path__)
 
1984
    else:
 
1985
        print bzrlib.__path__[0]
 
1986
 
 
1987
    print
 
1988
    print bzrlib.__copyright__
 
1989
    print "http://bazaar-vcs.org/"
 
1990
    print
 
1991
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
1992
    print "you may use, modify and redistribute it under the terms of the GNU"
 
1993
    print "General Public License version 2 or later."
3691
1994
 
3692
1995
 
3693
1996
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
 
 
 
1997
    """Show version of bzr."""
3701
1998
    @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
 
 
 
1999
    def run(self):
 
2000
        show_version()
3709
2001
 
3710
2002
class cmd_rocks(Command):
3711
 
    __doc__ = """Statement of optimism."""
3712
 
 
 
2003
    """Statement of optimism."""
3713
2004
    hidden = True
3714
 
 
3715
2005
    @display_command
3716
2006
    def run(self):
3717
 
        self.outf.write("It sure does!\n")
 
2007
        print "it sure does!"
3718
2008
 
3719
2009
 
3720
2010
class cmd_find_merge_base(Command):
3721
 
    __doc__ = """Find and print a base revision for merging two branches."""
 
2011
    """Find and print a base revision for merging two branches.
 
2012
    """
3722
2013
    # TODO: Options to specify revisions on either side, as if
3723
2014
    #       merging only part of the history.
3724
2015
    takes_args = ['branch', 'other']
3725
2016
    hidden = True
3726
 
 
 
2017
    
3727
2018
    @display_command
3728
2019
    def run(self, branch, other):
3729
 
        from bzrlib.revision import ensure_null
3730
 
 
 
2020
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
 
2021
        
3731
2022
        branch1 = Branch.open_containing(branch)[0]
3732
2023
        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)
 
2024
 
 
2025
        history_1 = branch1.revision_history()
 
2026
        history_2 = branch2.revision_history()
 
2027
 
 
2028
        last1 = branch1.last_revision()
 
2029
        last2 = branch2.last_revision()
 
2030
 
 
2031
        source = MultipleRevisionSources(branch1.repository, 
 
2032
                                         branch2.repository)
 
2033
        
 
2034
        base_rev_id = common_ancestor(last1, last2, source)
 
2035
 
 
2036
        print 'merge base is revision %s' % base_rev_id
3742
2037
 
3743
2038
 
3744
2039
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.
 
2040
    """Perform a three-way merge.
 
2041
    
 
2042
    The branch is the branch you will merge from.  By default, it will merge
 
2043
    the latest revision.  If you specify a revision, that revision will be
 
2044
    merged.  If you specify two revisions, the first will be used as a BASE,
 
2045
    and the second one as OTHER.  Revision numbers are always relative to the
 
2046
    specified branch.
3758
2047
 
3759
2048
    By default, bzr will try to merge in all new work from the other
3760
2049
    branch, automatically determining an appropriate base.  If this
3761
2050
    fails, you may need to give an explicit base.
3762
 
 
 
2051
    
3763
2052
    Merge will do its best to combine the changes in two branches, but there
3764
2053
    are some kinds of problems only a human can fix.  When it encounters those,
3765
2054
    it will mark a conflict.  A conflict means that you need to fix something,
3772
2061
    default, use --remember. The value will only be saved if the remote
3773
2062
    location can be accessed.
3774
2063
 
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
 
 
 
2064
    Examples:
 
2065
 
 
2066
    To merge the latest revision from bzr.dev
 
2067
    bzr merge ../bzr.dev
 
2068
 
 
2069
    To merge changes up to and including revision 82 from bzr.dev
 
2070
    bzr merge -r 82 ../bzr.dev
 
2071
 
 
2072
    To merge the changes introduced by 82, without previous changes:
 
2073
    bzr merge -r 81..82 ../bzr.dev
 
2074
    
3779
2075
    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'
 
2076
    --force is given.
 
2077
 
 
2078
    The following merge types are available:
3813
2079
    """
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
 
            ):
 
2080
    takes_args = ['branch?']
 
2081
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
 
2082
                     Option('show-base', help="Show base revision text in "
 
2083
                            "conflicts")]
 
2084
 
 
2085
    def help(self):
 
2086
        from merge import merge_type_help
 
2087
        from inspect import getdoc
 
2088
        return getdoc(self) + '\n' + merge_type_help() 
 
2089
 
 
2090
    def run(self, branch=None, revision=None, force=False, merge_type=None,
 
2091
            show_base=False, reprocess=False, remember=False):
3850
2092
        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
 
 
3860
 
        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)
 
2093
            merge_type = Merge3Merger
 
2094
 
 
2095
        tree = WorkingTree.open_containing(u'.')[0]
 
2096
 
 
2097
        if branch is not None:
 
2098
            try:
 
2099
                reader = bundle.read_bundle_from_url(branch)
 
2100
            except NotABundle:
 
2101
                pass # Continue on considering this url a Branch
 
2102
            else:
 
2103
                conflicts = merge_bundle(reader, tree, not force, merge_type,
 
2104
                                            reprocess, show_base)
 
2105
                if conflicts == 0:
 
2106
                    return 0
 
2107
                else:
 
2108
                    return 1
 
2109
 
 
2110
        branch = self._get_remembered_parent(tree, branch, 'Merging from')
 
2111
 
 
2112
        if revision is None or len(revision) < 1:
 
2113
            base = [None, None]
 
2114
            other = [branch, -1]
 
2115
            other_branch, path = Branch.open_containing(branch)
 
2116
        else:
 
2117
            if len(revision) == 1:
 
2118
                base = [None, None]
 
2119
                other_branch, path = Branch.open_containing(branch)
 
2120
                revno = revision[0].in_history(other_branch).revno
 
2121
                other = [branch, revno]
 
2122
            else:
 
2123
                assert len(revision) == 2
 
2124
                if None in revision:
 
2125
                    raise BzrCommandError(
 
2126
                        "Merge doesn't permit that revision specifier.")
 
2127
                other_branch, path = Branch.open_containing(branch)
 
2128
 
 
2129
                base = [branch, revision[0].in_history(other_branch).revno]
 
2130
                other = [branch, revision[1].in_history(other_branch).revno]
 
2131
 
 
2132
        if tree.branch.get_parent() is None or remember:
 
2133
            tree.branch.set_parent(other_branch.base)
 
2134
 
 
2135
        if path != "":
 
2136
            interesting_files = [path]
 
2137
        else:
 
2138
            interesting_files = None
3873
2139
        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:
 
2140
        try:
3877
2141
            try:
3878
 
                mergeable = bundle.read_mergeable_from_url(location,
3879
 
                    possible_transports=possible_transports)
3880
 
            except errors.NotABundle:
3881
 
                mergeable = None
 
2142
                conflict_count = merge(other, base, check_clean=(not force),
 
2143
                                       merge_type=merge_type,
 
2144
                                       reprocess=reprocess,
 
2145
                                       show_base=show_base,
 
2146
                                       pb=pb, file_list=interesting_files)
 
2147
            finally:
 
2148
                pb.finished()
 
2149
            if conflict_count != 0:
 
2150
                return 1
3882
2151
            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
2152
                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):
 
2153
        except errors.AmbiguousBase, e:
 
2154
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
2155
                 "candidates are:\n  "
 
2156
                 + "\n  ".join(e.bases)
 
2157
                 + "\n"
 
2158
                 "please specify an explicit base with -r,\n"
 
2159
                 "and (if you want) report this to the bzr developers\n")
 
2160
            log_error(m)
 
2161
 
 
2162
    # TODO: move up to common parent; this isn't merge-specific anymore. 
 
2163
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
4085
2164
        """Use tree.branch's parent if none was supplied.
4086
2165
 
4087
2166
        Report if the remembered location was used.
4088
2167
        """
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"
 
2168
        if supplied_location is not None:
 
2169
            return supplied_location
 
2170
        stored_location = tree.branch.get_parent()
4094
2171
        mutter("%s", stored_location)
4095
2172
        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)
 
2173
            raise BzrCommandError("No location specified or remembered")
 
2174
        display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
 
2175
        self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
4100
2176
        return stored_location
4101
2177
 
4102
2178
 
4103
2179
class cmd_remerge(Command):
4104
 
    __doc__ = """Redo a merge.
 
2180
    """Redo a merge.
4105
2181
 
4106
2182
    Use this if you want to try a different merge technique while resolving
4107
 
    conflicts.  Some merge techniques are better than others, and remerge
 
2183
    conflicts.  Some merge techniques are better than others, and remerge 
4108
2184
    lets you try different ones on different files.
4109
2185
 
4110
2186
    The options for remerge have the same meaning and defaults as the ones for
4111
2187
    merge.  The difference is that remerge can (only) be run when there is a
4112
2188
    pending merge, and it lets you specify particular files.
4113
2189
 
4114
 
    :Examples:
 
2190
    Examples:
 
2191
    $ bzr remerge --show-base
4115
2192
        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
 
 
 
2193
        conflict regions, in addition to the usual THIS and OTHER texts.
 
2194
 
 
2195
    $ bzr remerge --merge-type weave --reprocess foobar
4120
2196
        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
 
    """
 
2197
        additional processing to reduce the size of conflict regions.
 
2198
    
 
2199
    The following merge types are available:"""
4125
2200
    takes_args = ['file*']
4126
 
    takes_options = [
4127
 
            'merge-type',
4128
 
            'reprocess',
4129
 
            Option('show-base',
4130
 
                   help="Show base revision text in conflicts."),
4131
 
            ]
 
2201
    takes_options = ['merge-type', 'reprocess',
 
2202
                     Option('show-base', help="Show base revision text in "
 
2203
                            "conflicts")]
 
2204
 
 
2205
    def help(self):
 
2206
        from merge import merge_type_help
 
2207
        from inspect import getdoc
 
2208
        return getdoc(self) + '\n' + merge_type_help() 
4132
2209
 
4133
2210
    def run(self, file_list=None, merge_type=None, show_base=False,
4134
2211
            reprocess=False):
4135
 
        from bzrlib.conflicts import restore
 
2212
        from bzrlib.merge import merge_inner, transform_tree
4136
2213
        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])
 
2214
            merge_type = Merge3Merger
 
2215
        tree, file_list = tree_files(file_list)
 
2216
        tree.lock_write()
4182
2217
        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()
 
2218
            pending_merges = tree.pending_merges() 
 
2219
            if len(pending_merges) != 1:
 
2220
                raise BzrCommandError("Sorry, remerge only works after normal"
 
2221
                                      " merges.  Not cherrypicking or"
 
2222
                                      " multi-merges.")
 
2223
            repository = tree.branch.repository
 
2224
            base_revision = common_ancestor(tree.branch.last_revision(), 
 
2225
                                            pending_merges[0], repository)
 
2226
            base_tree = repository.revision_tree(base_revision)
 
2227
            other_tree = repository.revision_tree(pending_merges[0])
 
2228
            interesting_ids = None
 
2229
            new_conflicts = []
 
2230
            conflicts = tree.conflicts()
 
2231
            if file_list is not None:
 
2232
                interesting_ids = set()
 
2233
                for filename in file_list:
 
2234
                    file_id = tree.path2id(filename)
 
2235
                    if file_id is None:
 
2236
                        raise NotVersionedError(filename)
 
2237
                    interesting_ids.add(file_id)
 
2238
                    if tree.kind(file_id) != "directory":
 
2239
                        continue
 
2240
                    
 
2241
                    for name, ie in tree.inventory.iter_entries(file_id):
 
2242
                        interesting_ids.add(ie.file_id)
 
2243
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
2244
            transform_tree(tree, tree.basis_tree(), interesting_ids)
 
2245
            tree.set_conflicts(ConflictList(new_conflicts))
 
2246
            if file_list is None:
 
2247
                restore_files = list(tree.iter_conflicts())
 
2248
            else:
 
2249
                restore_files = file_list
 
2250
            for filename in restore_files:
 
2251
                try:
 
2252
                    restore(tree.abspath(filename))
 
2253
                except NotConflicted:
 
2254
                    pass
 
2255
            conflicts = merge_inner(tree.branch, other_tree, base_tree,
 
2256
                                    this_tree=tree,
 
2257
                                    interesting_ids=interesting_ids, 
 
2258
                                    other_rev_id=pending_merges[0], 
 
2259
                                    merge_type=merge_type, 
 
2260
                                    show_base=show_base,
 
2261
                                    reprocess=reprocess)
4189
2262
        finally:
4190
 
            tree.set_parent_ids(parents)
 
2263
            tree.unlock()
4191
2264
        if conflicts > 0:
4192
2265
            return 1
4193
2266
        else:
4194
2267
            return 0
4195
2268
 
4196
 
 
4197
2269
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.
 
2270
    """Reverse all changes since the last commit.
 
2271
 
 
2272
    Only versioned files are affected.  Specify filenames to revert only 
 
2273
    those files.  By default, any files that are changed will be backed up
 
2274
    first.  Backup files have a '~' appended to their name.
4241
2275
    """
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
 
        ]
 
2276
    takes_options = ['revision', 'no-backup']
4250
2277
    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)
 
2278
    aliases = ['merge-revert']
 
2279
 
 
2280
    def run(self, revision=None, no_backup=False, file_list=None):
 
2281
        from bzrlib.commands import parse_spec
 
2282
        if file_list is not None:
 
2283
            if len(file_list) == 0:
 
2284
                raise BzrCommandError("No files specified")
 
2285
        else:
 
2286
            file_list = []
 
2287
        
 
2288
        tree, file_list = tree_files(file_list)
 
2289
        if revision is None:
 
2290
            # FIXME should be tree.last_revision
 
2291
            rev_id = tree.last_revision()
 
2292
        elif len(revision) != 1:
 
2293
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
2294
        else:
 
2295
            rev_id = revision[0].in_history(tree.branch).rev_id
 
2296
        pb = ui.ui_factory.nested_progress_bar()
 
2297
        try:
 
2298
            tree.revert(file_list, 
 
2299
                        tree.branch.repository.revision_tree(rev_id),
 
2300
                        not no_backup, pb)
 
2301
        finally:
 
2302
            pb.finished()
4266
2303
 
4267
2304
 
4268
2305
class cmd_assert_fail(Command):
4269
 
    __doc__ = """Test reporting of assertion failures"""
4270
 
    # intended just for use in testing
4271
 
 
 
2306
    """Test reporting of assertion failures"""
4272
2307
    hidden = True
4273
 
 
4274
2308
    def run(self):
4275
 
        raise AssertionError("always fails")
 
2309
        assert False, "always fails"
4276
2310
 
4277
2311
 
4278
2312
class cmd_help(Command):
4279
 
    __doc__ = """Show help on a command or other topic.
4280
 
    """
 
2313
    """Show help on a command or other topic.
4281
2314
 
4282
 
    _see_also = ['topics']
4283
 
    takes_options = [
4284
 
            Option('long', 'Show help on all commands.'),
4285
 
            ]
 
2315
    For a list of all available commands, say 'bzr help commands'."""
 
2316
    takes_options = [Option('long', 'show help on all commands')]
4286
2317
    takes_args = ['topic?']
4287
2318
    aliases = ['?', '--help', '-?', '-h']
4288
 
 
 
2319
    
4289
2320
    @display_command
4290
2321
    def run(self, topic=None, long=False):
4291
 
        import bzrlib.help
 
2322
        import help
4292
2323
        if topic is None and long:
4293
2324
            topic = "commands"
4294
 
        bzrlib.help.help(topic)
 
2325
        help.help(topic)
4295
2326
 
4296
2327
 
4297
2328
class cmd_shell_complete(Command):
4298
 
    __doc__ = """Show appropriate completions for context.
 
2329
    """Show appropriate completions for context.
4299
2330
 
4300
 
    For a list of all available commands, say 'bzr shell-complete'.
4301
 
    """
 
2331
    For a list of all available commands, say 'bzr shell-complete'."""
4302
2332
    takes_args = ['context?']
4303
2333
    aliases = ['s-c']
4304
2334
    hidden = True
4305
 
 
 
2335
    
4306
2336
    @display_command
4307
2337
    def run(self, context=None):
4308
2338
        import shellcomplete
4309
2339
        shellcomplete.shellcomplete(context)
4310
2340
 
4311
2341
 
 
2342
class cmd_fetch(Command):
 
2343
    """Copy in history from another branch but don't merge it.
 
2344
 
 
2345
    This is an internal method used for pull and merge."""
 
2346
    hidden = True
 
2347
    takes_args = ['from_branch', 'to_branch']
 
2348
    def run(self, from_branch, to_branch):
 
2349
        from bzrlib.fetch import Fetcher
 
2350
        from_b = Branch.open(from_branch)
 
2351
        to_b = Branch.open(to_branch)
 
2352
        Fetcher(to_b, from_b)
 
2353
 
 
2354
 
4312
2355
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']
 
2356
    """Show unmerged/unpulled revisions between two branches.
 
2357
 
 
2358
    OTHER_BRANCH may be local or remote."""
4348
2359
    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
 
        ]
 
2360
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
 
2361
                     Option('mine-only', 
 
2362
                            'Display changes in the local branch only'),
 
2363
                     Option('theirs-only', 
 
2364
                            'Display changes in the remote branch only'), 
 
2365
                     'log-format',
 
2366
                     'line',
 
2367
                     'long', 
 
2368
                     'short',
 
2369
                     'show-ids',
 
2370
                     'verbose'
 
2371
                     ]
4371
2372
    encoding_type = 'replace'
4372
2373
 
4373
2374
    @display_command
4374
2375
    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
 
 
 
2376
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
 
2377
            show_ids=False, verbose=False):
 
2378
        from bzrlib.missing import find_unmerged, iter_log_data
 
2379
        from bzrlib.log import log_formatter
 
2380
        local_branch = Branch.open_containing(u".")[0]
4401
2381
        parent = local_branch.get_parent()
4402
2382
        if other_branch is None:
4403
2383
            other_branch = parent
4404
2384
            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
 
 
 
2385
                raise BzrCommandError("No missing location known or specified.")
 
2386
            print "Using last location: " + local_branch.get_parent()
4412
2387
        remote_branch = Branch.open(other_branch)
4413
2388
        if remote_branch.base == local_branch.base:
4414
2389
            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()
 
2390
        local_branch.lock_read()
 
2391
        try:
 
2392
            remote_branch.lock_read()
 
2393
            try:
 
2394
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
 
2395
                if (log_format == None):
 
2396
                    default = local_branch.get_config().log_format()
 
2397
                    log_format = get_log_format(long=long, short=short, 
 
2398
                                                line=line, default=default)
 
2399
                lf = log_formatter(log_format,
 
2400
                                   to_file=self.outf,
 
2401
                                   show_ids=show_ids,
 
2402
                                   show_timezone='original')
 
2403
                if reverse is False:
 
2404
                    local_extra.reverse()
 
2405
                    remote_extra.reverse()
 
2406
                if local_extra and not theirs_only:
 
2407
                    print "You have %d extra revision(s):" % len(local_extra)
 
2408
                    for data in iter_log_data(local_extra, local_branch.repository,
 
2409
                                              verbose):
 
2410
                        lf.show(*data)
 
2411
                    printed_local = True
 
2412
                else:
 
2413
                    printed_local = False
 
2414
                if remote_extra and not mine_only:
 
2415
                    if printed_local is True:
 
2416
                        print "\n\n"
 
2417
                    print "You are missing %d revision(s):" % len(remote_extra)
 
2418
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
 
2419
                                              verbose):
 
2420
                        lf.show(*data)
 
2421
                if not remote_extra and not local_extra:
 
2422
                    status_code = 0
 
2423
                    print "Branches are up to date."
 
2424
                else:
 
2425
                    status_code = 1
 
2426
            finally:
 
2427
                remote_branch.unlock()
 
2428
        finally:
 
2429
            local_branch.unlock()
4476
2430
        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)
 
2431
            local_branch.lock_write()
 
2432
            try:
 
2433
                # handle race conditions - a parent might be set while we run.
 
2434
                if local_branch.get_parent() is None:
 
2435
                    local_branch.set_parent(remote_branch.base)
 
2436
            finally:
 
2437
                local_branch.unlock()
4481
2438
        return status_code
4482
2439
 
4483
2440
 
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
2441
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
 
 
 
2442
    """List plugins"""
 
2443
    hidden = True
4540
2444
    @display_command
4541
 
    def run(self, verbose=False):
 
2445
    def run(self):
4542
2446
        import bzrlib.plugin
4543
2447
        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)
 
2448
        for name, plugin in bzrlib.plugin.all_plugins().items():
 
2449
            if hasattr(plugin, '__path__'):
 
2450
                print plugin.__path__[0]
 
2451
            elif hasattr(plugin, '__file__'):
 
2452
                print plugin.__file__
 
2453
            else:
 
2454
                print `plugin`
 
2455
                
 
2456
            d = getdoc(plugin)
4551
2457
            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")
 
2458
                print '\t', d.split('\n')[0]
4562
2459
 
4563
2460
 
4564
2461
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.')]
 
2462
    """Show testament (signing-form) of a revision."""
 
2463
    takes_options = ['revision', 'long', 
 
2464
                     Option('strict', help='Produce a strict-format'
 
2465
                            ' testament')]
4571
2466
    takes_args = ['branch?']
4572
2467
    @display_command
4573
2468
    def run(self, branch=u'.', revision=None, long=False, strict=False):
4576
2471
            testament_class = StrictTestament
4577
2472
        else:
4578
2473
            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())
 
2474
        b = WorkingTree.open_containing(branch)[0].branch
 
2475
        b.lock_read()
 
2476
        try:
 
2477
            if revision is None:
 
2478
                rev_id = b.last_revision()
 
2479
            else:
 
2480
                rev_id = revision[0].in_history(b).rev_id
 
2481
            t = testament_class.from_revision(b.repository, rev_id)
 
2482
            if long:
 
2483
                sys.stdout.writelines(t.as_text_lines())
 
2484
            else:
 
2485
                sys.stdout.write(t.as_short_text())
 
2486
        finally:
 
2487
            b.unlock()
4593
2488
 
4594
2489
 
4595
2490
class cmd_annotate(Command):
4596
 
    __doc__ = """Show the origin of each line in a file.
 
2491
    """Show the origin of each line in a file.
4597
2492
 
4598
2493
    This prints out the given file with an annotation on the left side
4599
2494
    indicating which revision, author and date introduced the change.
4600
2495
 
4601
 
    If the origin is the same for a run of consecutive lines, it is
 
2496
    If the origin is the same for a run of consecutive lines, it is 
4602
2497
    shown only at the top, unless the --all option is given.
4603
2498
    """
4604
2499
    # TODO: annotate directories; showing when each file was last changed
4605
 
    # TODO: if the working copy is modified, show annotations on that
 
2500
    # TODO: if the working copy is modified, show annotations on that 
4606
2501
    #       with new uncommitted lines marked
4607
2502
    aliases = ['ann', 'blame', 'praise']
4608
2503
    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',
 
2504
    takes_options = [Option('all', help='show annotations on all lines'),
 
2505
                     Option('long', help='show date in annotations'),
 
2506
                     'revision'
4614
2507
                     ]
4615
 
    encoding_type = 'exact'
4616
2508
 
4617
2509
    @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)
 
2510
    def run(self, filename, all=False, long=False, revision=None):
 
2511
        from bzrlib.annotate import annotate_file
 
2512
        tree, relpath = WorkingTree.open_containing(filename)
 
2513
        branch = tree.branch
 
2514
        branch.lock_read()
 
2515
        try:
 
2516
            if revision is None:
 
2517
                revision_id = branch.last_revision()
 
2518
            elif len(revision) != 1:
 
2519
                raise BzrCommandError('bzr annotate --revision takes exactly 1 argument')
 
2520
            else:
 
2521
                revision_id = revision[0].in_history(branch).rev_id
 
2522
            file_id = tree.inventory.path2id(relpath)
 
2523
            tree = branch.repository.revision_tree(revision_id)
 
2524
            file_version = tree.inventory[file_id].revision
 
2525
            annotate_file(branch, file_version, file_id, long, all, sys.stdout)
 
2526
        finally:
 
2527
            branch.unlock()
4644
2528
 
4645
2529
 
4646
2530
class cmd_re_sign(Command):
4647
 
    __doc__ = """Create a digital signature for an existing revision."""
 
2531
    """Create a digital signature for an existing revision."""
4648
2532
    # TODO be able to replace existing ones.
4649
2533
 
4650
2534
    hidden = True # is this right ?
4651
2535
    takes_args = ['revision_id*']
4652
 
    takes_options = ['directory', 'revision']
4653
 
 
4654
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
2536
    takes_options = ['revision']
 
2537
    
 
2538
    def run(self, revision_id_list=None, revision=None):
 
2539
        import bzrlib.gpg as gpg
4655
2540
        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')
 
2541
            raise BzrCommandError('You can only supply one of revision_id or --revision')
4657
2542
        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
 
2543
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
2544
        b = WorkingTree.open_containing(u'.')[0].branch
4665
2545
        gpg_strategy = gpg.GPGStrategy(b.get_config())
4666
2546
        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()
 
2547
            for revision_id in revision_id_list:
 
2548
                b.repository.sign_revision(revision_id, gpg_strategy)
4676
2549
        elif revision is not None:
4677
2550
            if len(revision) == 1:
4678
2551
                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()
 
2552
                b.repository.sign_revision(rev_id, gpg_strategy)
4687
2553
            elif len(revision) == 2:
4688
2554
                # are they both on rh- if so we can walk between them
4689
2555
                # might be nice to have a range helper for arbitrary
4693
2559
                if to_revid is None:
4694
2560
                    to_revno = b.revno()
4695
2561
                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()
 
2562
                    raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
 
2563
                for revno in range(from_revno, to_revno + 1):
 
2564
                    b.repository.sign_revision(b.get_rev_id(revno), 
 
2565
                                               gpg_strategy)
4707
2566
            else:
4708
 
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
 
2567
                raise BzrCommandError('Please supply either one revision, or a range.')
4709
2568
 
4710
2569
 
4711
2570
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.
 
2571
    """Bind the current branch to a master branch.
 
2572
 
 
2573
    After binding, commits must succeed on the master branch
 
2574
    before they are executed on the local one.
4721
2575
    """
4722
2576
 
4723
 
    _see_also = ['checkouts', 'unbind']
4724
 
    takes_args = ['location?']
4725
 
    takes_options = ['directory']
 
2577
    takes_args = ['location']
 
2578
    takes_options = []
4726
2579
 
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')
 
2580
    def run(self, location=None):
 
2581
        b, relpath = Branch.open_containing(u'.')
4742
2582
        b_other = Branch.open(location)
4743
2583
        try:
4744
2584
            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
 
2585
        except DivergedBranches:
 
2586
            raise BzrCommandError('These branches have diverged.'
 
2587
                                  ' Try merging, and then bind again.')
4750
2588
 
4751
2589
 
4752
2590
class cmd_unbind(Command):
4753
 
    __doc__ = """Convert the current checkout into a regular branch.
 
2591
    """Unbind the current branch from its master branch.
4754
2592
 
4755
 
    After unbinding, the local branch is considered independent and subsequent
4756
 
    commits will be local only.
 
2593
    After unbinding, the local branch is considered independent.
 
2594
    All subsequent commits will be local.
4757
2595
    """
4758
2596
 
4759
 
    _see_also = ['checkouts', 'bind']
4760
2597
    takes_args = []
4761
 
    takes_options = ['directory']
 
2598
    takes_options = []
4762
2599
 
4763
 
    def run(self, directory=u'.'):
4764
 
        b, relpath = Branch.open_containing(directory)
 
2600
    def run(self):
 
2601
        b, relpath = Branch.open_containing(u'.')
4765
2602
        if not b.unbind():
4766
 
            raise errors.BzrCommandError('Local branch is not bound')
 
2603
            raise BzrCommandError('Local branch is not bound')
4767
2604
 
4768
2605
 
4769
2606
class cmd_uncommit(Command):
4770
 
    __doc__ = """Remove the last committed revision.
 
2607
    """Remove the last committed revision.
4771
2608
 
4772
2609
    --verbose will print out what is being removed.
4773
2610
    --dry-run will go through all the motions, but not actually
4774
2611
    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.
 
2612
    
 
2613
    In the future, uncommit will create a revision bundle, which can then
 
2614
    be re-applied.
4783
2615
    """
4784
2616
 
4785
2617
    # TODO: jam 20060108 Add an option to allow uncommit to remove
4786
2618
    # unreferenced information in 'branch-as-repository' branches.
4787
2619
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
4788
2620
    # information in shared branches as well.
4789
 
    _see_also = ['commit']
4790
2621
    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
 
                    ]
 
2622
                    Option('dry-run', help='Don\'t actually make changes'),
 
2623
                    Option('force', help='Say yes to all questions.')]
4798
2624
    takes_args = ['location?']
4799
2625
    aliases = []
4800
 
    encoding_type = 'replace'
4801
2626
 
4802
 
    def run(self, location=None,
 
2627
    def run(self, location=None, 
4803
2628
            dry_run=False, verbose=False,
4804
 
            revision=None, force=False, local=False):
 
2629
            revision=None, force=False):
 
2630
        from bzrlib.log import log_formatter
 
2631
        import sys
 
2632
        from bzrlib.uncommit import uncommit
 
2633
 
4805
2634
        if location is None:
4806
2635
            location = u'.'
4807
2636
        control, relpath = bzrdir.BzrDir.open_containing(location)
4812
2641
            tree = None
4813
2642
            b = control.open_branch()
4814
2643
 
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
2644
        if revision is None:
4829
 
            revno = last_revno
4830
 
            rev_id = last_rev_id
 
2645
            revno = b.revno()
 
2646
            rev_id = b.last_revision()
4831
2647
        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)
 
2648
            revno, rev_id = revision[0].in_history(b)
 
2649
        if rev_id is None:
 
2650
            print 'No revisions to uncommit.'
 
2651
 
 
2652
        for r in range(revno, b.revno()+1):
 
2653
            rev_id = b.get_rev_id(r)
 
2654
            lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
 
2655
            lf.show(r, b.repository.get_revision(rev_id), None)
4855
2656
 
4856
2657
        if dry_run:
4857
 
            self.outf.write('Dry-run, pretending to remove'
4858
 
                            ' the above revisions.\n')
 
2658
            print 'Dry-run, pretending to remove the above revisions.'
 
2659
            if not force:
 
2660
                val = raw_input('Press <enter> to continue')
4859
2661
        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)
 
2662
            print 'The above revision(s) will be removed.'
 
2663
            if not force:
 
2664
                val = raw_input('Are you sure [y/N]? ')
 
2665
                if val.lower() not in ('y', 'yes'):
 
2666
                    print 'Canceled'
 
2667
                    return 0
 
2668
 
4872
2669
        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)
 
2670
                revno=revno)
4876
2671
 
4877
2672
 
4878
2673
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.
 
2674
    """Break a dead lock on a repository, branch or working directory.
4883
2675
 
4884
2676
    CAUTION: Locks should only be broken when you are sure that the process
4885
2677
    holding the lock has been stopped.
4886
2678
 
4887
 
    You can get information on what locks are open via the 'bzr info
4888
 
    [location]' command.
4889
 
 
4890
 
    :Examples:
 
2679
    You can get information on what locks are open via the 'bzr info' command.
 
2680
    
 
2681
    example:
4891
2682
        bzr break-lock
4892
 
        bzr break-lock bzr+ssh://example.com/bzr/foo
4893
 
        bzr break-lock --conf ~/.bazaar
4894
2683
    """
4895
 
 
4896
2684
    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
2685
 
4904
 
    def run(self, location=None, config=False, force=False):
 
2686
    def run(self, location=None, show=False):
4905
2687
        if location is None:
4906
2688
            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)
 
2689
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
2690
        try:
 
2691
            control.break_lock()
 
2692
        except NotImplementedError:
 
2693
            pass
 
2694
        
 
2695
 
 
2696
 
 
2697
# command-line interpretation helper for merge-related commands
 
2698
def merge(other_revision, base_revision,
 
2699
          check_clean=True, ignore_zero=False,
 
2700
          this_dir=None, backup_files=False, merge_type=Merge3Merger,
 
2701
          file_list=None, show_base=False, reprocess=False,
 
2702
          pb=DummyProgress()):
 
2703
    """Merge changes into a tree.
 
2704
 
 
2705
    base_revision
 
2706
        list(path, revno) Base for three-way merge.  
 
2707
        If [None, None] then a base will be automatically determined.
 
2708
    other_revision
 
2709
        list(path, revno) Other revision for three-way merge.
 
2710
    this_dir
 
2711
        Directory to merge changes into; '.' by default.
 
2712
    check_clean
 
2713
        If true, this_dir must have no uncommitted changes before the
 
2714
        merge begins.
 
2715
    ignore_zero - If true, suppress the "zero conflicts" message when 
 
2716
        there are no conflicts; should be set when doing something we expect
 
2717
        to complete perfectly.
 
2718
    file_list - If supplied, merge only changes to selected files.
 
2719
 
 
2720
    All available ancestors of other_revision and base_revision are
 
2721
    automatically pulled into the branch.
 
2722
 
 
2723
    The revno may be -1 to indicate the last revision on the branch, which is
 
2724
    the typical case.
 
2725
 
 
2726
    This function is intended for use from the command line; programmatic
 
2727
    clients might prefer to call merge.merge_inner(), which has less magic 
 
2728
    behavior.
 
2729
    """
 
2730
    from bzrlib.merge import Merger
 
2731
    if this_dir is None:
 
2732
        this_dir = u'.'
 
2733
    this_tree = WorkingTree.open_containing(this_dir)[0]
 
2734
    if show_base and not merge_type is Merge3Merger:
 
2735
        raise BzrCommandError("Show-base is not supported for this merge"
 
2736
                              " type. %s" % merge_type)
 
2737
    if reprocess and not merge_type.supports_reprocess:
 
2738
        raise BzrCommandError("Conflict reduction is not supported for merge"
 
2739
                              " type %s." % merge_type)
 
2740
    if reprocess and show_base:
 
2741
        raise BzrCommandError("Cannot do conflict reduction and show base.")
 
2742
    try:
 
2743
        merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
 
2744
        merger.pp = ProgressPhase("Merge phase", 5, pb)
 
2745
        merger.pp.next_phase()
 
2746
        merger.check_basis(check_clean)
 
2747
        merger.set_other(other_revision)
 
2748
        merger.pp.next_phase()
 
2749
        merger.set_base(base_revision)
 
2750
        if merger.base_rev_id == merger.other_rev_id:
 
2751
            note('Nothing to do.')
 
2752
            return 0
 
2753
        merger.backup_files = backup_files
 
2754
        merger.merge_type = merge_type 
 
2755
        merger.set_interesting_files(file_list)
 
2756
        merger.show_base = show_base 
 
2757
        merger.reprocess = reprocess
 
2758
        conflicts = merger.do_merge()
 
2759
        if file_list is None:
 
2760
            merger.set_pending()
 
2761
    finally:
 
2762
        pb.clear()
 
2763
    return conflicts
 
2764
 
 
2765
 
 
2766
# these get imported and then picked up by the scan for cmd_*
 
2767
# TODO: Some more consistent way to split command definitions across files;
 
2768
# we do need to load at least some information about them to know of 
 
2769
# aliases.  ideally we would avoid loading the implementation until the
 
2770
# details were needed.
 
2771
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
2772
from bzrlib.bundle.commands import cmd_bundle_revisions
 
2773
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
2774
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
 
2775
        cmd_weave_plan_merge, cmd_weave_merge_text