~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: 2010-10-13 07:04:50 UTC
  • mfrom: (5447.2.2 work)
  • Revision ID: pqm@pqm.ubuntu.com-20101013070450-xmn9cpnli5qnmrt8
(vila) Tweak the release process based on ML discussion (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

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