/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Andrew Bennetts
  • Date: 2010-04-13 04:33:55 UTC
  • mfrom: (5147 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5149.
  • Revision ID: andrew.bennetts@canonical.com-20100413043355-lg3id0uwtju0k3zs
MergeĀ lp:bzr.

Show diffs side-by-side

added added

removed removed

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