~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-31 00:27:39 UTC
  • mfrom: (4664.1.1 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20090831002739-vd6487doda1b2k9h
(robertc) Fix bug 416732 by not adding root directories to expected
        items when checking non rich root repositories. (Robert Collins)

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) 2004, 2005, 2006, 2007, 2008, 2009 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
 
19
19
import os
20
 
from StringIO import StringIO
21
20
 
22
21
from bzrlib.lazy_import import lazy_import
23
22
lazy_import(globals(), """
24
23
import codecs
 
24
import cStringIO
25
25
import sys
26
26
import time
27
27
 
29
29
from bzrlib import (
30
30
    bugtracker,
31
31
    bundle,
 
32
    btree_index,
32
33
    bzrdir,
33
34
    delta,
34
35
    config,
35
36
    errors,
36
37
    globbing,
37
 
    ignores,
 
38
    hooks,
38
39
    log,
39
40
    merge as _mod_merge,
40
41
    merge_directive,
41
42
    osutils,
42
43
    reconfigure,
 
44
    rename_map,
43
45
    revision as _mod_revision,
44
46
    symbol_versioning,
45
47
    transport,
46
 
    tree as _mod_tree,
47
48
    ui,
48
49
    urlutils,
 
50
    views,
49
51
    )
50
52
from bzrlib.branch import Branch
51
53
from bzrlib.conflicts import ConflictList
52
 
from bzrlib.revisionspec import RevisionSpec
 
54
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
53
55
from bzrlib.smtp_connection import SMTPConnection
54
56
from bzrlib.workingtree import WorkingTree
55
57
""")
56
58
 
57
59
from bzrlib.commands import Command, display_command
58
 
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
59
 
from bzrlib.trace import mutter, note, warning, is_quiet, info
60
 
 
61
 
 
62
 
def tree_files(file_list, default_branch=u'.'):
 
60
from bzrlib.option import (
 
61
    ListOption,
 
62
    Option,
 
63
    RegistryOption,
 
64
    custom_help,
 
65
    _parse_revision_str,
 
66
    )
 
67
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
 
68
 
 
69
 
 
70
def tree_files(file_list, default_branch=u'.', canonicalize=True,
 
71
    apply_view=True):
63
72
    try:
64
 
        return internal_tree_files(file_list, default_branch)
 
73
        return internal_tree_files(file_list, default_branch, canonicalize,
 
74
            apply_view)
65
75
    except errors.FileInWrongBranch, e:
66
76
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
67
77
                                     (e.path, file_list[0]))
68
78
 
69
79
 
 
80
def tree_files_for_add(file_list):
 
81
    """
 
82
    Return a tree and list of absolute paths from a file list.
 
83
 
 
84
    Similar to tree_files, but add handles files a bit differently, so it a
 
85
    custom implementation.  In particular, MutableTreeTree.smart_add expects
 
86
    absolute paths, which it immediately converts to relative paths.
 
87
    """
 
88
    # FIXME Would be nice to just return the relative paths like
 
89
    # internal_tree_files does, but there are a large number of unit tests
 
90
    # that assume the current interface to mutabletree.smart_add
 
91
    if file_list:
 
92
        tree, relpath = WorkingTree.open_containing(file_list[0])
 
93
        if tree.supports_views():
 
94
            view_files = tree.views.lookup_view()
 
95
            if view_files:
 
96
                for filename in file_list:
 
97
                    if not osutils.is_inside_any(view_files, filename):
 
98
                        raise errors.FileOutsideView(filename, view_files)
 
99
        file_list = file_list[:]
 
100
        file_list[0] = tree.abspath(relpath)
 
101
    else:
 
102
        tree = WorkingTree.open_containing(u'.')[0]
 
103
        if tree.supports_views():
 
104
            view_files = tree.views.lookup_view()
 
105
            if view_files:
 
106
                file_list = view_files
 
107
                view_str = views.view_display_str(view_files)
 
108
                note("Ignoring files outside view. View is %s" % view_str)
 
109
    return tree, file_list
 
110
 
 
111
 
 
112
def _get_one_revision(command_name, revisions):
 
113
    if revisions is None:
 
114
        return None
 
115
    if len(revisions) != 1:
 
116
        raise errors.BzrCommandError(
 
117
            'bzr %s --revision takes exactly one revision identifier' % (
 
118
                command_name,))
 
119
    return revisions[0]
 
120
 
 
121
 
 
122
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
 
123
    """Get a revision tree. Not suitable for commands that change the tree.
 
124
    
 
125
    Specifically, the basis tree in dirstate trees is coupled to the dirstate
 
126
    and doing a commit/uncommit/pull will at best fail due to changing the
 
127
    basis revision data.
 
128
 
 
129
    If tree is passed in, it should be already locked, for lifetime management
 
130
    of the trees internal cached state.
 
131
    """
 
132
    if branch is None:
 
133
        branch = tree.branch
 
134
    if revisions is None:
 
135
        if tree is not None:
 
136
            rev_tree = tree.basis_tree()
 
137
        else:
 
138
            rev_tree = branch.basis_tree()
 
139
    else:
 
140
        revision = _get_one_revision(command_name, revisions)
 
141
        rev_tree = revision.as_tree(branch)
 
142
    return rev_tree
 
143
 
 
144
 
70
145
# XXX: Bad function name; should possibly also be a class method of
71
146
# WorkingTree rather than a function.
72
 
def internal_tree_files(file_list, default_branch=u'.'):
 
147
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
 
148
    apply_view=True):
73
149
    """Convert command-line paths to a WorkingTree and relative paths.
74
150
 
75
151
    This is typically used for command-line processors that take one or
77
153
 
78
154
    The filenames given are not required to exist.
79
155
 
80
 
    :param file_list: Filenames to convert.  
 
156
    :param file_list: Filenames to convert.
81
157
 
82
158
    :param default_branch: Fallback tree path to use if file_list is empty or
83
159
        None.
84
160
 
 
161
    :param apply_view: if True and a view is set, apply it or check that
 
162
        specified files are within it
 
163
 
85
164
    :return: workingtree, [relative_paths]
86
165
    """
87
166
    if file_list is None or len(file_list) == 0:
88
 
        return WorkingTree.open_containing(default_branch)[0], file_list
 
167
        tree = WorkingTree.open_containing(default_branch)[0]
 
168
        if tree.supports_views() and apply_view:
 
169
            view_files = tree.views.lookup_view()
 
170
            if view_files:
 
171
                file_list = view_files
 
172
                view_str = views.view_display_str(view_files)
 
173
                note("Ignoring files outside view. View is %s" % view_str)
 
174
        return tree, file_list
89
175
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
90
 
    return tree, safe_relpath_files(tree, file_list)
91
 
 
92
 
 
93
 
def safe_relpath_files(tree, file_list):
 
176
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
177
        apply_view=apply_view)
 
178
 
 
179
 
 
180
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
94
181
    """Convert file_list into a list of relpaths in tree.
95
182
 
96
183
    :param tree: A tree to operate on.
97
184
    :param file_list: A list of user provided paths or None.
 
185
    :param apply_view: if True and a view is set, apply it or check that
 
186
        specified files are within it
98
187
    :return: A list of relative paths.
99
188
    :raises errors.PathNotChild: When a provided path is in a different tree
100
189
        than tree.
101
190
    """
102
191
    if file_list is None:
103
192
        return None
 
193
    if tree.supports_views() and apply_view:
 
194
        view_files = tree.views.lookup_view()
 
195
    else:
 
196
        view_files = []
104
197
    new_list = []
 
198
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
 
199
    # doesn't - fix that up here before we enter the loop.
 
200
    if canonicalize:
 
201
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
 
202
    else:
 
203
        fixer = tree.relpath
105
204
    for filename in file_list:
106
205
        try:
107
 
            new_list.append(tree.relpath(osutils.dereference_path(filename)))
 
206
            relpath = fixer(osutils.dereference_path(filename))
 
207
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
208
                raise errors.FileOutsideView(filename, view_files)
 
209
            new_list.append(relpath)
108
210
        except errors.PathNotChild:
109
211
            raise errors.FileInWrongBranch(tree.branch, filename)
110
212
    return new_list
111
213
 
112
214
 
 
215
def _get_view_info_for_change_reporter(tree):
 
216
    """Get the view information from a tree for change reporting."""
 
217
    view_info = None
 
218
    try:
 
219
        current_view = tree.views.get_view_info()[0]
 
220
        if current_view is not None:
 
221
            view_info = (current_view, tree.views.lookup_view())
 
222
    except errors.ViewsNotSupported:
 
223
        pass
 
224
    return view_info
 
225
 
 
226
 
113
227
# TODO: Make sure no commands unconditionally use the working directory as a
114
228
# branch.  If a filename argument is used, the first of them should be used to
115
229
# specify the branch.  (Perhaps this can be factored out into some kind of
145
259
 
146
260
    To see ignored files use 'bzr ignored'.  For details on the
147
261
    changes to file texts, use 'bzr diff'.
148
 
    
 
262
 
149
263
    Note that --short or -S gives status flags for each item, similar
150
264
    to Subversion's status command. To get output similar to svn -q,
151
265
    use bzr status -SV.
155
269
    files or directories is reported.  If a directory is given, status
156
270
    is reported for everything inside that directory.
157
271
 
 
272
    Before merges are committed, the pending merge tip revisions are
 
273
    shown. To see all pending merge revisions, use the -v option.
 
274
    To skip the display of pending merge information altogether, use
 
275
    the no-pending option or specify a file/directory.
 
276
 
158
277
    If a revision argument is given, the status is calculated against
159
278
    that revision, or between two revisions if two are provided.
160
279
    """
161
 
    
 
280
 
162
281
    # TODO: --no-recurse, --recurse options
163
 
    
 
282
 
164
283
    takes_args = ['file*']
165
 
    takes_options = ['show-ids', 'revision', 'change',
 
284
    takes_options = ['show-ids', 'revision', 'change', 'verbose',
166
285
                     Option('short', help='Use short status indicators.',
167
286
                            short_name='S'),
168
287
                     Option('versioned', help='Only show versioned files.',
174
293
 
175
294
    encoding_type = 'replace'
176
295
    _see_also = ['diff', 'revert', 'status-flags']
177
 
    
 
296
 
178
297
    @display_command
179
298
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
180
 
            versioned=False, no_pending=False):
 
299
            versioned=False, no_pending=False, verbose=False):
181
300
        from bzrlib.status import show_tree_status
182
301
 
183
302
        if revision and len(revision) > 2:
197
316
        show_tree_status(tree, show_ids=show_ids,
198
317
                         specific_files=relfile_list, revision=revision,
199
318
                         to_file=self.outf, short=short, versioned=versioned,
200
 
                         show_pending=(not no_pending))
 
319
                         show_pending=(not no_pending), verbose=verbose)
201
320
 
202
321
 
203
322
class cmd_cat_revision(Command):
204
323
    """Write out metadata for a revision.
205
 
    
 
324
 
206
325
    The revision to print can either be specified by a specific
207
326
    revision identifier, or you can use --revision.
208
327
    """
212
331
    takes_options = ['revision']
213
332
    # cat-revision is more for frontends so should be exact
214
333
    encoding = 'strict'
215
 
    
 
334
 
216
335
    @display_command
217
336
    def run(self, revision_id=None, revision=None):
218
337
        if revision_id is not None and revision is not None:
239
358
                                                 ' revision.')
240
359
                rev_id = rev.as_revision_id(b)
241
360
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
242
 
    
 
361
 
 
362
 
 
363
class cmd_dump_btree(Command):
 
364
    """Dump the contents of a btree index file to stdout.
 
365
 
 
366
    PATH is a btree index file, it can be any URL. This includes things like
 
367
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
 
368
 
 
369
    By default, the tuples stored in the index file will be displayed. With
 
370
    --raw, we will uncompress the pages, but otherwise display the raw bytes
 
371
    stored in the index.
 
372
    """
 
373
 
 
374
    # TODO: Do we want to dump the internal nodes as well?
 
375
    # TODO: It would be nice to be able to dump the un-parsed information,
 
376
    #       rather than only going through iter_all_entries. However, this is
 
377
    #       good enough for a start
 
378
    hidden = True
 
379
    encoding_type = 'exact'
 
380
    takes_args = ['path']
 
381
    takes_options = [Option('raw', help='Write the uncompressed bytes out,'
 
382
                                        ' rather than the parsed tuples.'),
 
383
                    ]
 
384
 
 
385
    def run(self, path, raw=False):
 
386
        dirname, basename = osutils.split(path)
 
387
        t = transport.get_transport(dirname)
 
388
        if raw:
 
389
            self._dump_raw_bytes(t, basename)
 
390
        else:
 
391
            self._dump_entries(t, basename)
 
392
 
 
393
    def _get_index_and_bytes(self, trans, basename):
 
394
        """Create a BTreeGraphIndex and raw bytes."""
 
395
        bt = btree_index.BTreeGraphIndex(trans, basename, None)
 
396
        bytes = trans.get_bytes(basename)
 
397
        bt._file = cStringIO.StringIO(bytes)
 
398
        bt._size = len(bytes)
 
399
        return bt, bytes
 
400
 
 
401
    def _dump_raw_bytes(self, trans, basename):
 
402
        import zlib
 
403
 
 
404
        # We need to parse at least the root node.
 
405
        # This is because the first page of every row starts with an
 
406
        # uncompressed header.
 
407
        bt, bytes = self._get_index_and_bytes(trans, basename)
 
408
        for page_idx, page_start in enumerate(xrange(0, len(bytes),
 
409
                                                     btree_index._PAGE_SIZE)):
 
410
            page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
 
411
            page_bytes = bytes[page_start:page_end]
 
412
            if page_idx == 0:
 
413
                self.outf.write('Root node:\n')
 
414
                header_end, data = bt._parse_header_from_bytes(page_bytes)
 
415
                self.outf.write(page_bytes[:header_end])
 
416
                page_bytes = data
 
417
            self.outf.write('\nPage %d\n' % (page_idx,))
 
418
            decomp_bytes = zlib.decompress(page_bytes)
 
419
            self.outf.write(decomp_bytes)
 
420
            self.outf.write('\n')
 
421
 
 
422
    def _dump_entries(self, trans, basename):
 
423
        try:
 
424
            st = trans.stat(basename)
 
425
        except errors.TransportNotPossible:
 
426
            # We can't stat, so we'll fake it because we have to do the 'get()'
 
427
            # anyway.
 
428
            bt, _ = self._get_index_and_bytes(trans, basename)
 
429
        else:
 
430
            bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
 
431
        for node in bt.iter_all_entries():
 
432
            # Node is made up of:
 
433
            # (index, key, value, [references])
 
434
            self.outf.write('%s\n' % (node[1:],))
 
435
 
243
436
 
244
437
class cmd_remove_tree(Command):
245
438
    """Remove the working tree from a given branch/checkout.
250
443
    To re-create the working tree, use "bzr checkout".
251
444
    """
252
445
    _see_also = ['checkout', 'working-trees']
253
 
 
254
446
    takes_args = ['location?']
 
447
    takes_options = [
 
448
        Option('force',
 
449
               help='Remove the working tree even if it has '
 
450
                    'uncommitted changes.'),
 
451
        ]
255
452
 
256
 
    def run(self, location='.'):
 
453
    def run(self, location='.', force=False):
257
454
        d = bzrdir.BzrDir.open(location)
258
 
        
 
455
 
259
456
        try:
260
457
            working = d.open_workingtree()
261
458
        except errors.NoWorkingTree:
262
459
            raise errors.BzrCommandError("No working tree to remove")
263
460
        except errors.NotLocalUrl:
264
 
            raise errors.BzrCommandError("You cannot remove the working tree of a "
265
 
                                         "remote path")
266
 
        
 
461
            raise errors.BzrCommandError("You cannot remove the working tree"
 
462
                                         " of a remote path")
 
463
        if not force:
 
464
            # XXX: What about pending merges ? -- vila 20090629
 
465
            if working.has_changes(working.basis_tree()):
 
466
                raise errors.UncommittedChanges(working)
 
467
 
267
468
        working_path = working.bzrdir.root_transport.base
268
469
        branch_path = working.branch.bzrdir.root_transport.base
269
470
        if working_path != branch_path:
270
 
            raise errors.BzrCommandError("You cannot remove the working tree from "
271
 
                                         "a lightweight checkout")
272
 
        
 
471
            raise errors.BzrCommandError("You cannot remove the working tree"
 
472
                                         " from a lightweight checkout")
 
473
 
273
474
        d.destroy_workingtree()
274
 
        
 
475
 
275
476
 
276
477
class cmd_revno(Command):
277
478
    """Show current revision number.
281
482
 
282
483
    _see_also = ['info']
283
484
    takes_args = ['location?']
 
485
    takes_options = [
 
486
        Option('tree', help='Show revno of working tree'),
 
487
        ]
284
488
 
285
489
    @display_command
286
 
    def run(self, location=u'.'):
287
 
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
288
 
        self.outf.write('\n')
 
490
    def run(self, tree=False, location=u'.'):
 
491
        if tree:
 
492
            try:
 
493
                wt = WorkingTree.open_containing(location)[0]
 
494
                wt.lock_read()
 
495
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
496
                raise errors.NoWorkingTree(location)
 
497
            try:
 
498
                revid = wt.last_revision()
 
499
                try:
 
500
                    revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
501
                except errors.NoSuchRevision:
 
502
                    revno_t = ('???',)
 
503
                revno = ".".join(str(n) for n in revno_t)
 
504
            finally:
 
505
                wt.unlock()
 
506
        else:
 
507
            b = Branch.open_containing(location)[0]
 
508
            b.lock_read()
 
509
            try:
 
510
                revno = b.revno()
 
511
            finally:
 
512
                b.unlock()
 
513
 
 
514
        self.outf.write(str(revno) + '\n')
289
515
 
290
516
 
291
517
class cmd_revision_info(Command):
293
519
    """
294
520
    hidden = True
295
521
    takes_args = ['revision_info*']
296
 
    takes_options = ['revision']
 
522
    takes_options = [
 
523
        'revision',
 
524
        Option('directory',
 
525
            help='Branch to examine, '
 
526
                 'rather than the one containing the working directory.',
 
527
            short_name='d',
 
528
            type=unicode,
 
529
            ),
 
530
        Option('tree', help='Show revno of working tree'),
 
531
        ]
297
532
 
298
533
    @display_command
299
 
    def run(self, revision=None, revision_info_list=[]):
300
 
 
301
 
        revs = []
302
 
        if revision is not None:
303
 
            revs.extend(revision)
304
 
        if revision_info_list is not None:
305
 
            for rev in revision_info_list:
306
 
                revs.append(RevisionSpec.from_string(rev))
307
 
 
308
 
        b = Branch.open_containing(u'.')[0]
309
 
 
310
 
        if len(revs) == 0:
311
 
            revs.append(RevisionSpec.from_string('-1'))
312
 
 
313
 
        for rev in revs:
314
 
            revision_id = rev.as_revision_id(b)
315
 
            try:
316
 
                revno = '%4d' % (b.revision_id_to_revno(revision_id))
317
 
            except errors.NoSuchRevision:
318
 
                dotted_map = b.get_revision_id_to_revno_map()
319
 
                revno = '.'.join(str(i) for i in dotted_map[revision_id])
320
 
            print '%s %s' % (revno, revision_id)
321
 
 
322
 
    
 
534
    def run(self, revision=None, directory=u'.', tree=False,
 
535
            revision_info_list=[]):
 
536
 
 
537
        try:
 
538
            wt = WorkingTree.open_containing(directory)[0]
 
539
            b = wt.branch
 
540
            wt.lock_read()
 
541
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
542
            wt = None
 
543
            b = Branch.open_containing(directory)[0]
 
544
            b.lock_read()
 
545
        try:
 
546
            revision_ids = []
 
547
            if revision is not None:
 
548
                revision_ids.extend(rev.as_revision_id(b) for rev in revision)
 
549
            if revision_info_list is not None:
 
550
                for rev_str in revision_info_list:
 
551
                    rev_spec = RevisionSpec.from_string(rev_str)
 
552
                    revision_ids.append(rev_spec.as_revision_id(b))
 
553
            # No arguments supplied, default to the last revision
 
554
            if len(revision_ids) == 0:
 
555
                if tree:
 
556
                    if wt is None:
 
557
                        raise errors.NoWorkingTree(directory)
 
558
                    revision_ids.append(wt.last_revision())
 
559
                else:
 
560
                    revision_ids.append(b.last_revision())
 
561
 
 
562
            revinfos = []
 
563
            maxlen = 0
 
564
            for revision_id in revision_ids:
 
565
                try:
 
566
                    dotted_revno = b.revision_id_to_dotted_revno(revision_id)
 
567
                    revno = '.'.join(str(i) for i in dotted_revno)
 
568
                except errors.NoSuchRevision:
 
569
                    revno = '???'
 
570
                maxlen = max(maxlen, len(revno))
 
571
                revinfos.append([revno, revision_id])
 
572
        finally:
 
573
            if wt is None:
 
574
                b.unlock()
 
575
            else:
 
576
                wt.unlock()
 
577
 
 
578
        for ri in revinfos:
 
579
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
 
580
 
 
581
 
323
582
class cmd_add(Command):
324
583
    """Add specified files or directories.
325
584
 
343
602
    you should never need to explicitly add a directory, they'll just
344
603
    get added when you add a file in the directory.
345
604
 
346
 
    --dry-run will show which files would be added, but not actually 
 
605
    --dry-run will show which files would be added, but not actually
347
606
    add them.
348
607
 
349
608
    --file-ids-from will try to use the file ids from the supplied path.
353
612
    branches that will be merged later (without showing the two different
354
613
    adds as a conflict). It is also useful when merging another project
355
614
    into a subdirectory of this one.
 
615
    
 
616
    Any files matching patterns in the ignore list will not be added
 
617
    unless they are explicitly mentioned.
356
618
    """
357
619
    takes_args = ['file*']
358
620
    takes_options = [
366
628
               help='Lookup file ids from this tree.'),
367
629
        ]
368
630
    encoding_type = 'replace'
369
 
    _see_also = ['remove']
 
631
    _see_also = ['remove', 'ignore']
370
632
 
371
633
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
372
634
            file_ids_from=None):
392
654
            base_tree.lock_read()
393
655
        try:
394
656
            file_list = self._maybe_expand_globs(file_list)
395
 
            if file_list:
396
 
                tree = WorkingTree.open_containing(file_list[0])[0]
397
 
            else:
398
 
                tree = WorkingTree.open_containing(u'.')[0]
 
657
            tree, file_list = tree_files_for_add(file_list)
399
658
            added, ignored = tree.smart_add(file_list, not
400
659
                no_recurse, action=action, save=not dry_run)
401
660
        finally:
405
664
            if verbose:
406
665
                for glob in sorted(ignored.keys()):
407
666
                    for path in ignored[glob]:
408
 
                        self.outf.write("ignored %s matching \"%s\"\n" 
 
667
                        self.outf.write("ignored %s matching \"%s\"\n"
409
668
                                        % (path, glob))
410
 
            else:
411
 
                match_len = 0
412
 
                for glob, paths in ignored.items():
413
 
                    match_len += len(paths)
414
 
                self.outf.write("ignored %d file(s).\n" % match_len)
415
 
            self.outf.write("If you wish to add some of these files,"
416
 
                            " please add them by name.\n")
417
669
 
418
670
 
419
671
class cmd_mkdir(Command):
438
690
 
439
691
    takes_args = ['filename']
440
692
    hidden = True
441
 
    
 
693
 
442
694
    @display_command
443
695
    def run(self, filename):
444
696
        # TODO: jam 20050106 Can relpath return a munged path if
474
726
        if kind and kind not in ['file', 'directory', 'symlink']:
475
727
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
476
728
 
 
729
        revision = _get_one_revision('inventory', revision)
477
730
        work_tree, file_list = tree_files(file_list)
478
731
        work_tree.lock_read()
479
732
        try:
480
733
            if revision is not None:
481
 
                if len(revision) > 1:
482
 
                    raise errors.BzrCommandError(
483
 
                        'bzr inventory --revision takes exactly one revision'
484
 
                        ' identifier')
485
 
                revision_id = revision[0].as_revision_id(work_tree.branch)
486
 
                tree = work_tree.branch.repository.revision_tree(revision_id)
 
734
                tree = revision.as_tree(work_tree.branch)
487
735
 
488
736
                extra_trees = [work_tree]
489
737
                tree.lock_read()
539
787
    takes_args = ['names*']
540
788
    takes_options = [Option("after", help="Move only the bzr identifier"
541
789
        " of the file, because the file has already been moved."),
 
790
        Option('auto', help='Automatically guess renames.'),
 
791
        Option('dry-run', help='Avoid making changes when guessing renames.'),
542
792
        ]
543
793
    aliases = ['move', 'rename']
544
794
    encoding_type = 'replace'
545
795
 
546
 
    def run(self, names_list, after=False):
 
796
    def run(self, names_list, after=False, auto=False, dry_run=False):
 
797
        if auto:
 
798
            return self.run_auto(names_list, after, dry_run)
 
799
        elif dry_run:
 
800
            raise errors.BzrCommandError('--dry-run requires --auto.')
547
801
        if names_list is None:
548
802
            names_list = []
549
 
 
550
803
        if len(names_list) < 2:
551
804
            raise errors.BzrCommandError("missing file argument")
552
 
        tree, rel_names = tree_files(names_list)
553
 
        tree.lock_write()
 
805
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
806
        tree.lock_tree_write()
554
807
        try:
555
808
            self._run(tree, names_list, rel_names, after)
556
809
        finally:
557
810
            tree.unlock()
558
811
 
 
812
    def run_auto(self, names_list, after, dry_run):
 
813
        if names_list is not None and len(names_list) > 1:
 
814
            raise errors.BzrCommandError('Only one path may be specified to'
 
815
                                         ' --auto.')
 
816
        if after:
 
817
            raise errors.BzrCommandError('--after cannot be specified with'
 
818
                                         ' --auto.')
 
819
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
820
        work_tree.lock_tree_write()
 
821
        try:
 
822
            rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
823
        finally:
 
824
            work_tree.unlock()
 
825
 
559
826
    def _run(self, tree, names_list, rel_names, after):
560
827
        into_existing = osutils.isdir(names_list[-1])
561
828
        if into_existing and len(names_list) == 2:
569
836
                into_existing = False
570
837
            else:
571
838
                inv = tree.inventory
572
 
                from_id = tree.path2id(rel_names[0])
 
839
                # 'fix' the case of a potential 'from'
 
840
                from_id = tree.path2id(
 
841
                            tree.get_canonical_inventory_path(rel_names[0]))
573
842
                if (not osutils.lexists(names_list[0]) and
574
843
                    from_id and inv.get_file_kind(from_id) == "directory"):
575
844
                    into_existing = False
576
845
        # move/rename
577
846
        if into_existing:
578
847
            # move into existing directory
 
848
            # All entries reference existing inventory items, so fix them up
 
849
            # for cicp file-systems.
 
850
            rel_names = tree.get_canonical_inventory_paths(rel_names)
579
851
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
580
852
                self.outf.write("%s => %s\n" % pair)
581
853
        else:
583
855
                raise errors.BzrCommandError('to mv multiple files the'
584
856
                                             ' destination must be a versioned'
585
857
                                             ' directory')
586
 
            tree.rename_one(rel_names[0], rel_names[1], after=after)
587
 
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
 
858
 
 
859
            # for cicp file-systems: the src references an existing inventory
 
860
            # item:
 
861
            src = tree.get_canonical_inventory_path(rel_names[0])
 
862
            # Find the canonical version of the destination:  In all cases, the
 
863
            # parent of the target must be in the inventory, so we fetch the
 
864
            # canonical version from there (we do not always *use* the
 
865
            # canonicalized tail portion - we may be attempting to rename the
 
866
            # case of the tail)
 
867
            canon_dest = tree.get_canonical_inventory_path(rel_names[1])
 
868
            dest_parent = osutils.dirname(canon_dest)
 
869
            spec_tail = osutils.basename(rel_names[1])
 
870
            # For a CICP file-system, we need to avoid creating 2 inventory
 
871
            # entries that differ only by case.  So regardless of the case
 
872
            # we *want* to use (ie, specified by the user or the file-system),
 
873
            # we must always choose to use the case of any existing inventory
 
874
            # items.  The only exception to this is when we are attempting a
 
875
            # case-only rename (ie, canonical versions of src and dest are
 
876
            # the same)
 
877
            dest_id = tree.path2id(canon_dest)
 
878
            if dest_id is None or tree.path2id(src) == dest_id:
 
879
                # No existing item we care about, so work out what case we
 
880
                # are actually going to use.
 
881
                if after:
 
882
                    # If 'after' is specified, the tail must refer to a file on disk.
 
883
                    if dest_parent:
 
884
                        dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
 
885
                    else:
 
886
                        # pathjoin with an empty tail adds a slash, which breaks
 
887
                        # relpath :(
 
888
                        dest_parent_fq = tree.basedir
 
889
 
 
890
                    dest_tail = osutils.canonical_relpath(
 
891
                                    dest_parent_fq,
 
892
                                    osutils.pathjoin(dest_parent_fq, spec_tail))
 
893
                else:
 
894
                    # not 'after', so case as specified is used
 
895
                    dest_tail = spec_tail
 
896
            else:
 
897
                # Use the existing item so 'mv' fails with AlreadyVersioned.
 
898
                dest_tail = os.path.basename(canon_dest)
 
899
            dest = osutils.pathjoin(dest_parent, dest_tail)
 
900
            mutter("attempting to move %s => %s", src, dest)
 
901
            tree.rename_one(src, dest, after=after)
 
902
            self.outf.write("%s => %s\n" % (src, dest))
588
903
 
589
904
 
590
905
class cmd_pull(Command):
611
926
    with bzr send.
612
927
    """
613
928
 
614
 
    _see_also = ['push', 'update', 'status-flags']
 
929
    _see_also = ['push', 'update', 'status-flags', 'send']
615
930
    takes_options = ['remember', 'overwrite', 'revision',
616
931
        custom_help('verbose',
617
932
            help='Show logs of pulled revisions.'),
621
936
            short_name='d',
622
937
            type=unicode,
623
938
            ),
 
939
        Option('local',
 
940
            help="Perform a local pull in a bound "
 
941
                 "branch.  Local pulls are not applied to "
 
942
                 "the master branch."
 
943
            ),
624
944
        ]
625
945
    takes_args = ['location?']
626
946
    encoding_type = 'replace'
627
947
 
628
948
    def run(self, location=None, remember=False, overwrite=False,
629
949
            revision=None, verbose=False,
630
 
            directory=None):
 
950
            directory=None, local=False):
631
951
        # FIXME: too much stuff is in the command class
632
952
        revision_id = None
633
953
        mergeable = None
639
959
        except errors.NoWorkingTree:
640
960
            tree_to = None
641
961
            branch_to = Branch.open_containing(directory)[0]
 
962
        
 
963
        if local and not branch_to.get_bound_location():
 
964
            raise errors.LocalRequiresBoundBranch()
642
965
 
643
966
        possible_transports = []
644
967
        if location is not None:
660
983
                    self.outf.write("Using saved parent location: %s\n" % display_url)
661
984
                location = stored_loc
662
985
 
 
986
        revision = _get_one_revision('pull', revision)
663
987
        if mergeable is not None:
664
988
            if revision is not None:
665
989
                raise errors.BzrCommandError(
675
999
            if branch_to.get_parent() is None or remember:
676
1000
                branch_to.set_parent(branch_from.base)
677
1001
 
678
 
        if revision is not None:
679
 
            if len(revision) == 1:
680
 
                revision_id = revision[0].as_revision_id(branch_from)
681
 
            else:
682
 
                raise errors.BzrCommandError(
683
 
                    'bzr pull --revision takes one value.')
684
 
 
685
 
        branch_to.lock_write()
 
1002
        if branch_from is not branch_to:
 
1003
            branch_from.lock_read()
686
1004
        try:
687
 
            if tree_to is not None:
688
 
                change_reporter = delta._ChangeReporter(
689
 
                    unversioned_filter=tree_to.is_ignored)
690
 
                result = tree_to.pull(branch_from, overwrite, revision_id,
691
 
                                      change_reporter,
692
 
                                      possible_transports=possible_transports)
693
 
            else:
694
 
                result = branch_to.pull(branch_from, overwrite, revision_id)
695
 
 
696
 
            result.report(self.outf)
697
 
            if verbose and result.old_revid != result.new_revid:
698
 
                old_rh = list(
699
 
                    branch_to.repository.iter_reverse_revision_history(
700
 
                    result.old_revid))
701
 
                old_rh.reverse()
702
 
                new_rh = branch_to.revision_history()
703
 
                log.show_changed_revisions(branch_to, old_rh, new_rh,
704
 
                                           to_file=self.outf)
 
1005
            if revision is not None:
 
1006
                revision_id = revision.as_revision_id(branch_from)
 
1007
 
 
1008
            branch_to.lock_write()
 
1009
            try:
 
1010
                if tree_to is not None:
 
1011
                    view_info = _get_view_info_for_change_reporter(tree_to)
 
1012
                    change_reporter = delta._ChangeReporter(
 
1013
                        unversioned_filter=tree_to.is_ignored,
 
1014
                        view_info=view_info)
 
1015
                    result = tree_to.pull(
 
1016
                        branch_from, overwrite, revision_id, change_reporter,
 
1017
                        possible_transports=possible_transports, local=local)
 
1018
                else:
 
1019
                    result = branch_to.pull(
 
1020
                        branch_from, overwrite, revision_id, local=local)
 
1021
 
 
1022
                result.report(self.outf)
 
1023
                if verbose and result.old_revid != result.new_revid:
 
1024
                    log.show_branch_change(
 
1025
                        branch_to, self.outf, result.old_revno,
 
1026
                        result.old_revid)
 
1027
            finally:
 
1028
                branch_to.unlock()
705
1029
        finally:
706
 
            branch_to.unlock()
 
1030
            if branch_from is not branch_to:
 
1031
                branch_from.unlock()
707
1032
 
708
1033
 
709
1034
class cmd_push(Command):
710
1035
    """Update a mirror of this branch.
711
 
    
 
1036
 
712
1037
    The target branch will not have its working tree populated because this
713
1038
    is both expensive, and is not supported on remote file systems.
714
 
    
 
1039
 
715
1040
    Some smart servers or protocols *may* put the working tree in place in
716
1041
    the future.
717
1042
 
721
1046
 
722
1047
    If branches have diverged, you can use 'bzr push --overwrite' to replace
723
1048
    the other branch completely, discarding its unmerged changes.
724
 
    
 
1049
 
725
1050
    If you want to ensure you have the different changes in the other branch,
726
1051
    do a merge (see bzr help merge) from the other branch, and commit that.
727
1052
    After that you will be able to do a push without '--overwrite'.
756
1081
                'for the commit history. Only the work not present in the '
757
1082
                'referenced branch is included in the branch created.',
758
1083
            type=unicode),
 
1084
        Option('strict',
 
1085
               help='Refuse to push if there are uncommitted changes in'
 
1086
               ' the working tree, --no-strict disables the check.'),
759
1087
        ]
760
1088
    takes_args = ['location?']
761
1089
    encoding_type = 'replace'
763
1091
    def run(self, location=None, remember=False, overwrite=False,
764
1092
        create_prefix=False, verbose=False, revision=None,
765
1093
        use_existing_dir=False, directory=None, stacked_on=None,
766
 
        stacked=False):
 
1094
        stacked=False, strict=None):
767
1095
        from bzrlib.push import _show_push_branch
768
1096
 
769
 
        # Get the source branch and revision_id
770
1097
        if directory is None:
771
1098
            directory = '.'
772
 
        br_from = Branch.open_containing(directory)[0]
 
1099
        # Get the source branch
 
1100
        (tree, br_from,
 
1101
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1102
        if strict is None:
 
1103
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
 
1104
        if strict is None: strict = True # default value
 
1105
        # Get the tip's revision_id
 
1106
        revision = _get_one_revision('push', revision)
773
1107
        if revision is not None:
774
 
            if len(revision) == 1:
775
 
                revision_id = revision[0].in_history(br_from).rev_id
776
 
            else:
777
 
                raise errors.BzrCommandError(
778
 
                    'bzr push --revision takes one value.')
 
1108
            revision_id = revision.in_history(br_from).rev_id
779
1109
        else:
780
 
            revision_id = br_from.last_revision()
 
1110
            revision_id = None
 
1111
        if strict and tree is not None and revision_id is None:
 
1112
            if (tree.has_changes(tree.basis_tree())
 
1113
                or len(tree.get_parent_ids()) > 1):
 
1114
                raise errors.UncommittedChanges(
 
1115
                    tree, more='Use --no-strict to force the push.')
 
1116
            if tree.last_revision() != tree.branch.last_revision():
 
1117
                # The tree has lost sync with its branch, there is little
 
1118
                # chance that the user is aware of it but he can still force
 
1119
                # the push with --no-strict
 
1120
                raise errors.OutOfDateTree(
 
1121
                    tree, more='Use --no-strict to force the push.')
781
1122
 
782
1123
        # Get the stacked_on branch, if any
783
1124
        if stacked_on is not None:
816
1157
 
817
1158
 
818
1159
class cmd_branch(Command):
819
 
    """Create a new copy of a branch.
 
1160
    """Create a new branch that is a copy of an existing branch.
820
1161
 
821
1162
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
822
1163
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
833
1174
    takes_args = ['from_location', 'to_location?']
834
1175
    takes_options = ['revision', Option('hardlink',
835
1176
        help='Hard-link working tree files where possible.'),
 
1177
        Option('no-tree',
 
1178
            help="Create a branch without a working-tree."),
 
1179
        Option('switch',
 
1180
            help="Switch the checkout in the current directory "
 
1181
                 "to the new branch."),
836
1182
        Option('stacked',
837
1183
            help='Create a stacked branch referring to the source branch. '
838
1184
                'The new branch will depend on the availability of the source '
839
1185
                'branch for all operations.'),
 
1186
        Option('standalone',
 
1187
               help='Do not use a shared repository, even if available.'),
 
1188
        Option('use-existing-dir',
 
1189
               help='By default branch will fail if the target'
 
1190
                    ' directory exists, but does not already'
 
1191
                    ' have a control directory.  This flag will'
 
1192
                    ' allow branch to proceed.'),
840
1193
        ]
841
1194
    aliases = ['get', 'clone']
842
1195
 
843
1196
    def run(self, from_location, to_location=None, revision=None,
844
 
            hardlink=False, stacked=False):
 
1197
            hardlink=False, stacked=False, standalone=False, no_tree=False,
 
1198
            use_existing_dir=False, switch=False):
 
1199
        from bzrlib import switch as _mod_switch
845
1200
        from bzrlib.tag import _merge_tags_if_possible
846
 
        if revision is None:
847
 
            revision = [None]
848
 
        elif len(revision) > 1:
849
 
            raise errors.BzrCommandError(
850
 
                'bzr branch --revision takes exactly 1 revision value')
851
 
 
852
1201
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
853
1202
            from_location)
 
1203
        if (accelerator_tree is not None and
 
1204
            accelerator_tree.supports_content_filtering()):
 
1205
            accelerator_tree = None
 
1206
        revision = _get_one_revision('branch', revision)
854
1207
        br_from.lock_read()
855
1208
        try:
856
 
            if len(revision) == 1 and revision[0] is not None:
857
 
                revision_id = revision[0].as_revision_id(br_from)
 
1209
            if revision is not None:
 
1210
                revision_id = revision.as_revision_id(br_from)
858
1211
            else:
859
1212
                # FIXME - wt.last_revision, fallback to branch, fall back to
860
1213
                # None or perhaps NULL_REVISION to mean copy nothing
866
1219
            try:
867
1220
                to_transport.mkdir('.')
868
1221
            except errors.FileExists:
869
 
                raise errors.BzrCommandError('Target directory "%s" already'
870
 
                                             ' exists.' % to_location)
 
1222
                if not use_existing_dir:
 
1223
                    raise errors.BzrCommandError('Target directory "%s" '
 
1224
                        'already exists.' % to_location)
 
1225
                else:
 
1226
                    try:
 
1227
                        bzrdir.BzrDir.open_from_transport(to_transport)
 
1228
                    except errors.NotBranchError:
 
1229
                        pass
 
1230
                    else:
 
1231
                        raise errors.AlreadyBranchError(to_location)
871
1232
            except errors.NoSuchFile:
872
1233
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
873
1234
                                             % to_location)
876
1237
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
877
1238
                                            possible_transports=[to_transport],
878
1239
                                            accelerator_tree=accelerator_tree,
879
 
                                            hardlink=hardlink, stacked=stacked)
 
1240
                                            hardlink=hardlink, stacked=stacked,
 
1241
                                            force_new_repo=standalone,
 
1242
                                            create_tree_if_local=not no_tree,
 
1243
                                            source_branch=br_from)
880
1244
                branch = dir.open_branch()
881
1245
            except errors.NoSuchRevision:
882
1246
                to_transport.delete_tree('.')
883
1247
                msg = "The branch %s has no revision %s." % (from_location,
884
 
                    revision[0])
 
1248
                    revision)
885
1249
                raise errors.BzrCommandError(msg)
886
1250
            _merge_tags_if_possible(br_from, branch)
887
1251
            # If the source branch is stacked, the new branch may
893
1257
            except (errors.NotStacked, errors.UnstackableBranchFormat,
894
1258
                errors.UnstackableRepositoryFormat), e:
895
1259
                note('Branched %d revision(s).' % branch.revno())
 
1260
            if switch:
 
1261
                # Switch to the new branch
 
1262
                wt, _ = WorkingTree.open_containing('.')
 
1263
                _mod_switch.switch(wt.bzrdir, branch)
 
1264
                note('Switched to branch: %s',
 
1265
                    urlutils.unescape_for_display(branch.base, 'utf-8'))
896
1266
        finally:
897
1267
            br_from.unlock()
898
1268
 
904
1274
    the branch found in '.'. This is useful if you have removed the working tree
905
1275
    or if it was never created - i.e. if you pushed the branch to its current
906
1276
    location using SFTP.
907
 
    
 
1277
 
908
1278
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
909
1279
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
910
1280
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
938
1308
 
939
1309
    def run(self, branch_location=None, to_location=None, revision=None,
940
1310
            lightweight=False, files_from=None, hardlink=False):
941
 
        if revision is None:
942
 
            revision = [None]
943
 
        elif len(revision) > 1:
944
 
            raise errors.BzrCommandError(
945
 
                'bzr checkout --revision takes exactly 1 revision value')
946
1311
        if branch_location is None:
947
1312
            branch_location = osutils.getcwd()
948
1313
            to_location = branch_location
949
1314
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
950
1315
            branch_location)
 
1316
        revision = _get_one_revision('checkout', revision)
951
1317
        if files_from is not None:
952
1318
            accelerator_tree = WorkingTree.open(files_from)
953
 
        if len(revision) == 1 and revision[0] is not None:
954
 
            revision_id = revision[0].as_revision_id(source)
 
1319
        if revision is not None:
 
1320
            revision_id = revision.as_revision_id(source)
955
1321
        else:
956
1322
            revision_id = None
957
1323
        if to_location is None:
958
1324
            to_location = urlutils.derive_to_location(branch_location)
959
 
        # if the source and to_location are the same, 
 
1325
        # if the source and to_location are the same,
960
1326
        # and there is no working tree,
961
1327
        # then reconstitute a branch
962
1328
        if (osutils.abspath(to_location) ==
989
1355
            old_tree.lock_read()
990
1356
            try:
991
1357
                old_inv = old_tree.inventory
992
 
                renames = list(_mod_tree.find_renames(old_inv, new_inv))
 
1358
                renames = []
 
1359
                iterator = tree.iter_changes(old_tree, include_unchanged=True)
 
1360
                for f, paths, c, v, p, n, k, e in iterator:
 
1361
                    if paths[0] == paths[1]:
 
1362
                        continue
 
1363
                    if None in (paths):
 
1364
                        continue
 
1365
                    renames.append(paths)
993
1366
                renames.sort()
994
1367
                for old_name, new_name in renames:
995
1368
                    self.outf.write("%s => %s\n" % (old_name, new_name))
1001
1374
 
1002
1375
class cmd_update(Command):
1003
1376
    """Update a tree to have the latest code committed to its branch.
1004
 
    
 
1377
 
1005
1378
    This will perform a merge into the working tree, and may generate
1006
 
    conflicts. If you have any local changes, you will still 
 
1379
    conflicts. If you have any local changes, you will still
1007
1380
    need to commit them after the update for the update to be complete.
1008
 
    
1009
 
    If you want to discard your local changes, you can just do a 
 
1381
 
 
1382
    If you want to discard your local changes, you can just do a
1010
1383
    'bzr revert' instead of 'bzr commit' after the update.
1011
1384
    """
1012
1385
 
1034
1407
                    revno = tree.branch.revision_id_to_revno(last_rev)
1035
1408
                    note("Tree is up to date at revision %d." % (revno,))
1036
1409
                    return 0
 
1410
            view_info = _get_view_info_for_change_reporter(tree)
1037
1411
            conflicts = tree.update(
1038
 
                delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1039
 
                possible_transports=possible_transports)
 
1412
                delta._ChangeReporter(unversioned_filter=tree.is_ignored,
 
1413
                view_info=view_info), possible_transports=possible_transports)
1040
1414
            revno = tree.branch.revision_id_to_revno(
1041
1415
                _mod_revision.ensure_null(tree.last_revision()))
1042
1416
            note('Updated to revision %d.' % (revno,))
1055
1429
    """Show information about a working tree, branch or repository.
1056
1430
 
1057
1431
    This command will show all known locations and formats associated to the
1058
 
    tree, branch or repository.  Statistical information is included with
1059
 
    each report.
 
1432
    tree, branch or repository.
 
1433
 
 
1434
    In verbose mode, statistical information is included with each report.
 
1435
    To see extended statistic information, use a verbosity level of 2 or
 
1436
    higher by specifying the verbose option multiple times, e.g. -vv.
1060
1437
 
1061
1438
    Branches and working trees will also report any missing revisions.
 
1439
 
 
1440
    :Examples:
 
1441
 
 
1442
      Display information on the format and related locations:
 
1443
 
 
1444
        bzr info
 
1445
 
 
1446
      Display the above together with extended format information and
 
1447
      basic statistics (like the number of files in the working tree and
 
1448
      number of revisions in the branch and repository):
 
1449
 
 
1450
        bzr info -v
 
1451
 
 
1452
      Display the above together with number of committers to the branch:
 
1453
 
 
1454
        bzr info -vv
1062
1455
    """
1063
1456
    _see_also = ['revno', 'working-trees', 'repositories']
1064
1457
    takes_args = ['location?']
1068
1461
    @display_command
1069
1462
    def run(self, location=None, verbose=False):
1070
1463
        if verbose:
1071
 
            noise_level = 2
 
1464
            noise_level = get_verbosity_level()
1072
1465
        else:
1073
1466
            noise_level = 0
1074
1467
        from bzrlib.info import show_bzrdir_info
1092
1485
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1093
1486
            safe='Only delete files if they can be'
1094
1487
                 ' safely recovered (default).',
1095
 
            keep="Don't delete any files.",
 
1488
            keep='Delete from bzr but leave the working copy.',
1096
1489
            force='Delete all the specified files, even if they can not be '
1097
1490
                'recovered and even if they are non-empty directories.')]
1098
1491
    aliases = ['rm', 'del']
1181
1574
 
1182
1575
    This can correct data mismatches that may have been caused by
1183
1576
    previous ghost operations or bzr upgrades. You should only
1184
 
    need to run this command if 'bzr check' or a bzr developer 
 
1577
    need to run this command if 'bzr check' or a bzr developer
1185
1578
    advises you to run it.
1186
1579
 
1187
1580
    If a second branch is provided, cross-branch reconciliation is
1189
1582
    id which was not present in very early bzr versions is represented
1190
1583
    correctly in both branches.
1191
1584
 
1192
 
    At the same time it is run it may recompress data resulting in 
 
1585
    At the same time it is run it may recompress data resulting in
1193
1586
    a potential saving in disk space or performance gain.
1194
1587
 
1195
1588
    The branch *MUST* be on a listable system such as local disk or sftp.
1251
1644
    Use this to create an empty branch, or before importing an
1252
1645
    existing project.
1253
1646
 
1254
 
    If there is a repository in a parent directory of the location, then 
 
1647
    If there is a repository in a parent directory of the location, then
1255
1648
    the history of the branch will be stored in the repository.  Otherwise
1256
1649
    init creates a standalone branch which carries its own history
1257
1650
    in the .bzr directory.
1277
1670
         RegistryOption('format',
1278
1671
                help='Specify a format for this branch. '
1279
1672
                'See "help formats".',
1280
 
                registry=bzrdir.format_registry,
1281
 
                converter=bzrdir.format_registry.make_bzrdir,
 
1673
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1674
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1282
1675
                value_switches=True,
1283
1676
                title="Branch Format",
1284
1677
                ),
1309
1702
                    "\nYou may supply --create-prefix to create all"
1310
1703
                    " leading parent directories."
1311
1704
                    % location)
1312
 
            _create_prefix(to_transport)
 
1705
            to_transport.create_prefix()
1313
1706
 
1314
1707
        try:
1315
 
            existing_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
 
1708
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1316
1709
        except errors.NotBranchError:
1317
1710
            # really a NotBzrDir error...
1318
1711
            create_branch = bzrdir.BzrDir.create_branch_convenience
1319
1712
            branch = create_branch(to_transport.base, format=format,
1320
1713
                                   possible_transports=[to_transport])
 
1714
            a_bzrdir = branch.bzrdir
1321
1715
        else:
1322
1716
            from bzrlib.transport.local import LocalTransport
1323
 
            if existing_bzrdir.has_branch():
 
1717
            if a_bzrdir.has_branch():
1324
1718
                if (isinstance(to_transport, LocalTransport)
1325
 
                    and not existing_bzrdir.has_workingtree()):
 
1719
                    and not a_bzrdir.has_workingtree()):
1326
1720
                        raise errors.BranchExistsWithoutWorkingTree(location)
1327
1721
                raise errors.AlreadyBranchError(location)
1328
 
            else:
1329
 
                branch = existing_bzrdir.create_branch()
1330
 
                existing_bzrdir.create_workingtree()
 
1722
            branch = a_bzrdir.create_branch()
 
1723
            a_bzrdir.create_workingtree()
1331
1724
        if append_revisions_only:
1332
1725
            try:
1333
1726
                branch.set_append_revisions_only(True)
1334
1727
            except errors.UpgradeRequired:
1335
1728
                raise errors.BzrCommandError('This branch format cannot be set'
1336
 
                    ' to append-revisions-only.  Try --experimental-branch6')
 
1729
                    ' to append-revisions-only.  Try --default.')
1337
1730
        if not is_quiet():
1338
 
            from bzrlib.info import show_bzrdir_info
1339
 
            show_bzrdir_info(bzrdir.BzrDir.open_containing_from_transport(
1340
 
                to_transport)[0], verbose=0, outfile=self.outf)
 
1731
            from bzrlib.info import describe_layout, describe_format
 
1732
            try:
 
1733
                tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
 
1734
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
1735
                tree = None
 
1736
            repository = branch.repository
 
1737
            layout = describe_layout(repository, branch, tree).lower()
 
1738
            format = describe_format(a_bzrdir, repository, branch, tree)
 
1739
            self.outf.write("Created a %s (format: %s)\n" % (layout, format))
 
1740
            if repository.is_shared():
 
1741
                #XXX: maybe this can be refactored into transport.path_or_url()
 
1742
                url = repository.bzrdir.root_transport.external_url()
 
1743
                try:
 
1744
                    url = urlutils.local_path_from_url(url)
 
1745
                except errors.InvalidURL:
 
1746
                    pass
 
1747
                self.outf.write("Using shared repository: %s\n" % url)
1341
1748
 
1342
1749
 
1343
1750
class cmd_init_repository(Command):
1367
1774
    takes_options = [RegistryOption('format',
1368
1775
                            help='Specify a format for this repository. See'
1369
1776
                                 ' "bzr help formats" for details.',
1370
 
                            registry=bzrdir.format_registry,
1371
 
                            converter=bzrdir.format_registry.make_bzrdir,
 
1777
                            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1778
                            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1372
1779
                            value_switches=True, title='Repository format'),
1373
1780
                     Option('no-trees',
1374
1781
                             help='Branches in the repository will default to'
1391
1798
        repo.set_make_working_trees(not no_trees)
1392
1799
        if not is_quiet():
1393
1800
            from bzrlib.info import show_bzrdir_info
1394
 
            show_bzrdir_info(bzrdir.BzrDir.open_containing_from_transport(
1395
 
                to_transport)[0], verbose=0, outfile=self.outf)
 
1801
            show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1396
1802
 
1397
1803
 
1398
1804
class cmd_diff(Command):
1399
1805
    """Show differences in the working tree, between revisions or branches.
1400
 
    
 
1806
 
1401
1807
    If no arguments are given, all changes for the current tree are listed.
1402
1808
    If files are given, only the changes in those files are listed.
1403
1809
    Remote and multiple branches can be compared by using the --old and
1502
1908
                                         ' one or two revision specifiers')
1503
1909
 
1504
1910
        old_tree, new_tree, specific_files, extra_trees = \
1505
 
                _get_trees_to_diff(file_list, revision, old, new)
1506
 
        return show_diff_trees(old_tree, new_tree, sys.stdout, 
 
1911
                _get_trees_to_diff(file_list, revision, old, new,
 
1912
                apply_view=True)
 
1913
        return show_diff_trees(old_tree, new_tree, sys.stdout,
1507
1914
                               specific_files=specific_files,
1508
1915
                               external_diff_options=diff_options,
1509
1916
                               old_label=old_label, new_label=new_label,
1628
2035
        raise errors.BzrCommandError(msg)
1629
2036
 
1630
2037
 
 
2038
def _parse_levels(s):
 
2039
    try:
 
2040
        return int(s)
 
2041
    except ValueError:
 
2042
        msg = "The levels argument must be an integer."
 
2043
        raise errors.BzrCommandError(msg)
 
2044
 
 
2045
 
1631
2046
class cmd_log(Command):
1632
 
    """Show log of a branch, file, or directory.
1633
 
 
1634
 
    By default show the log of the branch containing the working directory.
1635
 
 
1636
 
    To request a range of logs, you can use the command -r begin..end
1637
 
    -r revision requests a specific revision, -r ..end or -r begin.. are
1638
 
    also valid.
1639
 
 
1640
 
    :Examples:
1641
 
        Log the current branch::
1642
 
 
1643
 
            bzr log
1644
 
 
1645
 
        Log a file::
1646
 
 
1647
 
            bzr log foo.c
1648
 
 
1649
 
        Log the last 10 revisions of a branch::
1650
 
 
1651
 
            bzr log -r -10.. http://server/branch
 
2047
    """Show historical log for a branch or subset of a branch.
 
2048
 
 
2049
    log is bzr's default tool for exploring the history of a branch.
 
2050
    The branch to use is taken from the first parameter. If no parameters
 
2051
    are given, the branch containing the working directory is logged.
 
2052
    Here are some simple examples::
 
2053
 
 
2054
      bzr log                       log the current branch
 
2055
      bzr log foo.py                log a file in its branch
 
2056
      bzr log http://server/branch  log a branch on a server
 
2057
 
 
2058
    The filtering, ordering and information shown for each revision can
 
2059
    be controlled as explained below. By default, all revisions are
 
2060
    shown sorted (topologically) so that newer revisions appear before
 
2061
    older ones and descendants always appear before ancestors. If displayed,
 
2062
    merged revisions are shown indented under the revision in which they
 
2063
    were merged.
 
2064
 
 
2065
    :Output control:
 
2066
 
 
2067
      The log format controls how information about each revision is
 
2068
      displayed. The standard log formats are called ``long``, ``short``
 
2069
      and ``line``. The default is long. See ``bzr help log-formats``
 
2070
      for more details on log formats.
 
2071
 
 
2072
      The following options can be used to control what information is
 
2073
      displayed::
 
2074
 
 
2075
        -l N        display a maximum of N revisions
 
2076
        -n N        display N levels of revisions (0 for all, 1 for collapsed)
 
2077
        -v          display a status summary (delta) for each revision
 
2078
        -p          display a diff (patch) for each revision
 
2079
        --show-ids  display revision-ids (and file-ids), not just revnos
 
2080
 
 
2081
      Note that the default number of levels to display is a function of the
 
2082
      log format. If the -n option is not used, the standard log formats show
 
2083
      just the top level (mainline).
 
2084
 
 
2085
      Status summaries are shown using status flags like A, M, etc. To see
 
2086
      the changes explained using words like ``added`` and ``modified``
 
2087
      instead, use the -vv option.
 
2088
 
 
2089
    :Ordering control:
 
2090
 
 
2091
      To display revisions from oldest to newest, use the --forward option.
 
2092
      In most cases, using this option will have little impact on the total
 
2093
      time taken to produce a log, though --forward does not incrementally
 
2094
      display revisions like --reverse does when it can.
 
2095
 
 
2096
    :Revision filtering:
 
2097
 
 
2098
      The -r option can be used to specify what revision or range of revisions
 
2099
      to filter against. The various forms are shown below::
 
2100
 
 
2101
        -rX      display revision X
 
2102
        -rX..    display revision X and later
 
2103
        -r..Y    display up to and including revision Y
 
2104
        -rX..Y   display from X to Y inclusive
 
2105
 
 
2106
      See ``bzr help revisionspec`` for details on how to specify X and Y.
 
2107
      Some common examples are given below::
 
2108
 
 
2109
        -r-1                show just the tip
 
2110
        -r-10..             show the last 10 mainline revisions
 
2111
        -rsubmit:..         show what's new on this branch
 
2112
        -rancestor:path..   show changes since the common ancestor of this
 
2113
                            branch and the one at location path
 
2114
        -rdate:yesterday..  show changes since yesterday
 
2115
 
 
2116
      When logging a range of revisions using -rX..Y, log starts at
 
2117
      revision Y and searches back in history through the primary
 
2118
      ("left-hand") parents until it finds X. When logging just the
 
2119
      top level (using -n1), an error is reported if X is not found
 
2120
      along the way. If multi-level logging is used (-n0), X may be
 
2121
      a nested merge revision and the log will be truncated accordingly.
 
2122
 
 
2123
    :Path filtering:
 
2124
 
 
2125
      If parameters are given and the first one is not a branch, the log
 
2126
      will be filtered to show only those revisions that changed the
 
2127
      nominated files or directories.
 
2128
 
 
2129
      Filenames are interpreted within their historical context. To log a
 
2130
      deleted file, specify a revision range so that the file existed at
 
2131
      the end or start of the range.
 
2132
 
 
2133
      Historical context is also important when interpreting pathnames of
 
2134
      renamed files/directories. Consider the following example:
 
2135
 
 
2136
      * revision 1: add tutorial.txt
 
2137
      * revision 2: modify tutorial.txt
 
2138
      * revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
 
2139
 
 
2140
      In this case:
 
2141
 
 
2142
      * ``bzr log guide.txt`` will log the file added in revision 1
 
2143
 
 
2144
      * ``bzr log tutorial.txt`` will log the new file added in revision 3
 
2145
 
 
2146
      * ``bzr log -r2 -p tutorial.txt`` will show the changes made to
 
2147
        the original file in revision 2.
 
2148
 
 
2149
      * ``bzr log -r2 -p guide.txt`` will display an error message as there
 
2150
        was no file called guide.txt in revision 2.
 
2151
 
 
2152
      Renames are always followed by log. By design, there is no need to
 
2153
      explicitly ask for this (and no way to stop logging a file back
 
2154
      until it was last renamed).
 
2155
 
 
2156
    :Other filtering:
 
2157
 
 
2158
      The --message option can be used for finding revisions that match a
 
2159
      regular expression in a commit message.
 
2160
 
 
2161
    :Tips & tricks:
 
2162
 
 
2163
      GUI tools and IDEs are often better at exploring history than command
 
2164
      line tools. You may prefer qlog or glog from the QBzr and Bzr-Gtk packages
 
2165
      respectively for example. (TortoiseBzr uses qlog for displaying logs.) See
 
2166
      http://bazaar-vcs.org/BzrPlugins and http://bazaar-vcs.org/IDEIntegration.
 
2167
 
 
2168
      Web interfaces are often better at exploring history than command line
 
2169
      tools, particularly for branches on servers. You may prefer Loggerhead
 
2170
      or one of its alternatives. See http://bazaar-vcs.org/WebInterface.
 
2171
 
 
2172
      You may find it useful to add the aliases below to ``bazaar.conf``::
 
2173
 
 
2174
        [ALIASES]
 
2175
        tip = log -r-1
 
2176
        top = log -l10 --line
 
2177
        show = log -v -p
 
2178
 
 
2179
      ``bzr tip`` will then show the latest revision while ``bzr top``
 
2180
      will show the last 10 mainline revisions. To see the details of a
 
2181
      particular revision X,  ``bzr show -rX``.
 
2182
 
 
2183
      If you are interested in looking deeper into a particular merge X,
 
2184
      use ``bzr log -n0 -rX``.
 
2185
 
 
2186
      ``bzr log -v`` on a branch with lots of history is currently
 
2187
      very slow. A fix for this issue is currently under development.
 
2188
      With or without that fix, it is recommended that a revision range
 
2189
      be given when using the -v option.
 
2190
 
 
2191
      bzr has a generic full-text matching plugin, bzr-search, that can be
 
2192
      used to find revisions matching user names, commit messages, etc.
 
2193
      Among other features, this plugin can find all revisions containing
 
2194
      a list of words but not others.
 
2195
 
 
2196
      When exploring non-mainline history on large projects with deep
 
2197
      history, the performance of log can be greatly improved by installing
 
2198
      the historycache plugin. This plugin buffers historical information
 
2199
      trading disk space for faster speed.
1652
2200
    """
1653
 
 
1654
 
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
1655
 
 
1656
 
    takes_args = ['location?']
 
2201
    takes_args = ['file*']
 
2202
    _see_also = ['log-formats', 'revisionspec']
1657
2203
    takes_options = [
1658
2204
            Option('forward',
1659
2205
                   help='Show from oldest to newest.'),
1660
 
            Option('timezone',
1661
 
                   type=str,
1662
 
                   help='Display timezone as local, original, or utc.'),
 
2206
            'timezone',
1663
2207
            custom_help('verbose',
1664
2208
                   help='Show files changed in each revision.'),
1665
2209
            'show-ids',
1666
2210
            'revision',
 
2211
            Option('change',
 
2212
                   type=bzrlib.option._parse_revision_str,
 
2213
                   short_name='c',
 
2214
                   help='Show just the specified revision.'
 
2215
                   ' See also "help revisionspec".'),
1667
2216
            'log-format',
 
2217
            Option('levels',
 
2218
                   short_name='n',
 
2219
                   help='Number of levels to display - 0 for all, 1 for flat.',
 
2220
                   argname='N',
 
2221
                   type=_parse_levels),
1668
2222
            Option('message',
1669
2223
                   short_name='m',
1670
2224
                   help='Show revisions whose message matches this '
1675
2229
                   help='Limit the output to the first N revisions.',
1676
2230
                   argname='N',
1677
2231
                   type=_parse_limit),
 
2232
            Option('show-diff',
 
2233
                   short_name='p',
 
2234
                   help='Show changes made in each revision as a patch.'),
 
2235
            Option('include-merges',
 
2236
                   help='Show merged revisions like --levels 0 does.'),
1678
2237
            ]
1679
2238
    encoding_type = 'replace'
1680
2239
 
1681
2240
    @display_command
1682
 
    def run(self, location=None, timezone='original',
 
2241
    def run(self, file_list=None, timezone='original',
1683
2242
            verbose=False,
1684
2243
            show_ids=False,
1685
2244
            forward=False,
1686
2245
            revision=None,
 
2246
            change=None,
1687
2247
            log_format=None,
 
2248
            levels=None,
1688
2249
            message=None,
1689
 
            limit=None):
1690
 
        from bzrlib.log import show_log
 
2250
            limit=None,
 
2251
            show_diff=False,
 
2252
            include_merges=False):
 
2253
        from bzrlib.log import (
 
2254
            Logger,
 
2255
            make_log_request_dict,
 
2256
            _get_info_for_log_files,
 
2257
            )
1691
2258
        direction = (forward and 'forward') or 'reverse'
1692
 
        
1693
 
        # log everything
1694
 
        file_id = None
1695
 
        if location:
1696
 
            # find the file id to log:
1697
 
 
1698
 
            tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1699
 
                location)
1700
 
            if fp != '':
1701
 
                if tree is None:
1702
 
                    tree = b.basis_tree()
1703
 
                file_id = tree.path2id(fp)
 
2259
        if include_merges:
 
2260
            if levels is None:
 
2261
                levels = 0
 
2262
            else:
 
2263
                raise errors.BzrCommandError(
 
2264
                    '--levels and --include-merges are mutually exclusive')
 
2265
 
 
2266
        if change is not None:
 
2267
            if len(change) > 1:
 
2268
                raise errors.RangeInChangeOption()
 
2269
            if revision is not None:
 
2270
                raise errors.BzrCommandError(
 
2271
                    '--revision and --change are mutually exclusive')
 
2272
            else:
 
2273
                revision = change
 
2274
 
 
2275
        file_ids = []
 
2276
        filter_by_dir = False
 
2277
        if file_list:
 
2278
            # find the file ids to log and check for directory filtering
 
2279
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(revision,
 
2280
                file_list)
 
2281
            for relpath, file_id, kind in file_info_list:
1704
2282
                if file_id is None:
1705
2283
                    raise errors.BzrCommandError(
1706
 
                        "Path does not have any revision history: %s" %
1707
 
                        location)
 
2284
                        "Path unknown at end or start of revision range: %s" %
 
2285
                        relpath)
 
2286
                # If the relpath is the top of the tree, we log everything
 
2287
                if relpath == '':
 
2288
                    file_ids = []
 
2289
                    break
 
2290
                else:
 
2291
                    file_ids.append(file_id)
 
2292
                filter_by_dir = filter_by_dir or (
 
2293
                    kind in ['directory', 'tree-reference'])
1708
2294
        else:
1709
 
            # local dir only
1710
 
            # FIXME ? log the current subdir only RBC 20060203 
 
2295
            # log everything
 
2296
            # FIXME ? log the current subdir only RBC 20060203
1711
2297
            if revision is not None \
1712
2298
                    and len(revision) > 0 and revision[0].get_branch():
1713
2299
                location = revision[0].get_branch()
1715
2301
                location = '.'
1716
2302
            dir, relpath = bzrdir.BzrDir.open_containing(location)
1717
2303
            b = dir.open_branch()
 
2304
            rev1, rev2 = _get_revision_range(revision, b, self.name())
 
2305
 
 
2306
        # Decide on the type of delta & diff filtering to use
 
2307
        # TODO: add an --all-files option to make this configurable & consistent
 
2308
        if not verbose:
 
2309
            delta_type = None
 
2310
        else:
 
2311
            delta_type = 'full'
 
2312
        if not show_diff:
 
2313
            diff_type = None
 
2314
        elif file_ids:
 
2315
            diff_type = 'partial'
 
2316
        else:
 
2317
            diff_type = 'full'
1718
2318
 
1719
2319
        b.lock_read()
1720
2320
        try:
1721
 
            if revision is None:
1722
 
                rev1 = None
1723
 
                rev2 = None
1724
 
            elif len(revision) == 1:
1725
 
                rev1 = rev2 = revision[0].in_history(b)
1726
 
            elif len(revision) == 2:
1727
 
                if revision[1].get_branch() != revision[0].get_branch():
1728
 
                    # b is taken from revision[0].get_branch(), and
1729
 
                    # show_log will use its revision_history. Having
1730
 
                    # different branches will lead to weird behaviors.
1731
 
                    raise errors.BzrCommandError(
1732
 
                        "Log doesn't accept two revisions in different"
1733
 
                        " branches.")
1734
 
                rev1 = revision[0].in_history(b)
1735
 
                rev2 = revision[1].in_history(b)
1736
 
            else:
1737
 
                raise errors.BzrCommandError(
1738
 
                    'bzr log --revision takes one or two values.')
1739
 
 
 
2321
            # Build the log formatter
1740
2322
            if log_format is None:
1741
2323
                log_format = log.log_formatter_registry.get_default(b)
1742
 
 
1743
2324
            lf = log_format(show_ids=show_ids, to_file=self.outf,
1744
 
                            show_timezone=timezone)
1745
 
 
1746
 
            show_log(b,
1747
 
                     lf,
1748
 
                     file_id,
1749
 
                     verbose=verbose,
1750
 
                     direction=direction,
1751
 
                     start_revision=rev1,
1752
 
                     end_revision=rev2,
1753
 
                     search=message,
1754
 
                     limit=limit)
 
2325
                            show_timezone=timezone,
 
2326
                            delta_format=get_verbosity_level(),
 
2327
                            levels=levels,
 
2328
                            show_advice=levels is None)
 
2329
 
 
2330
            # Choose the algorithm for doing the logging. It's annoying
 
2331
            # having multiple code paths like this but necessary until
 
2332
            # the underlying repository format is faster at generating
 
2333
            # deltas or can provide everything we need from the indices.
 
2334
            # The default algorithm - match-using-deltas - works for
 
2335
            # multiple files and directories and is faster for small
 
2336
            # amounts of history (200 revisions say). However, it's too
 
2337
            # slow for logging a single file in a repository with deep
 
2338
            # history, i.e. > 10K revisions. In the spirit of "do no
 
2339
            # evil when adding features", we continue to use the
 
2340
            # original algorithm - per-file-graph - for the "single
 
2341
            # file that isn't a directory without showing a delta" case.
 
2342
            partial_history = revision and b.repository._format.supports_chks
 
2343
            match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2344
                or delta_type or partial_history)
 
2345
 
 
2346
            # Build the LogRequest and execute it
 
2347
            if len(file_ids) == 0:
 
2348
                file_ids = None
 
2349
            rqst = make_log_request_dict(
 
2350
                direction=direction, specific_fileids=file_ids,
 
2351
                start_revision=rev1, end_revision=rev2, limit=limit,
 
2352
                message_search=message, delta_type=delta_type,
 
2353
                diff_type=diff_type, _match_using_deltas=match_using_deltas)
 
2354
            Logger(b, rqst).show(lf)
1755
2355
        finally:
1756
2356
            b.unlock()
1757
2357
 
1758
2358
 
 
2359
def _get_revision_range(revisionspec_list, branch, command_name):
 
2360
    """Take the input of a revision option and turn it into a revision range.
 
2361
 
 
2362
    It returns RevisionInfo objects which can be used to obtain the rev_id's
 
2363
    of the desired revisions. It does some user input validations.
 
2364
    """
 
2365
    if revisionspec_list is None:
 
2366
        rev1 = None
 
2367
        rev2 = None
 
2368
    elif len(revisionspec_list) == 1:
 
2369
        rev1 = rev2 = revisionspec_list[0].in_history(branch)
 
2370
    elif len(revisionspec_list) == 2:
 
2371
        start_spec = revisionspec_list[0]
 
2372
        end_spec = revisionspec_list[1]
 
2373
        if end_spec.get_branch() != start_spec.get_branch():
 
2374
            # b is taken from revision[0].get_branch(), and
 
2375
            # show_log will use its revision_history. Having
 
2376
            # different branches will lead to weird behaviors.
 
2377
            raise errors.BzrCommandError(
 
2378
                "bzr %s doesn't accept two revisions in different"
 
2379
                " branches." % command_name)
 
2380
        rev1 = start_spec.in_history(branch)
 
2381
        # Avoid loading all of history when we know a missing
 
2382
        # end of range means the last revision ...
 
2383
        if end_spec.spec is None:
 
2384
            last_revno, last_revision_id = branch.last_revision_info()
 
2385
            rev2 = RevisionInfo(branch, last_revno, last_revision_id)
 
2386
        else:
 
2387
            rev2 = end_spec.in_history(branch)
 
2388
    else:
 
2389
        raise errors.BzrCommandError(
 
2390
            'bzr %s --revision takes one or two values.' % command_name)
 
2391
    return rev1, rev2
 
2392
 
 
2393
 
 
2394
def _revision_range_to_revid_range(revision_range):
 
2395
    rev_id1 = None
 
2396
    rev_id2 = None
 
2397
    if revision_range[0] is not None:
 
2398
        rev_id1 = revision_range[0].rev_id
 
2399
    if revision_range[1] is not None:
 
2400
        rev_id2 = revision_range[1].rev_id
 
2401
    return rev_id1, rev_id2
 
2402
 
1759
2403
def get_log_format(long=False, short=False, line=False, default='long'):
1760
2404
    log_format = default
1761
2405
    if long:
1791
2435
 
1792
2436
    _see_also = ['status', 'cat']
1793
2437
    takes_args = ['path?']
1794
 
    # TODO: Take a revision or remote path and list that tree instead.
1795
2438
    takes_options = [
1796
2439
            'verbose',
1797
2440
            'revision',
1798
 
            Option('non-recursive',
1799
 
                   help='Don\'t recurse into subdirectories.'),
 
2441
            Option('recursive', short_name='R',
 
2442
                   help='Recurse into subdirectories.'),
1800
2443
            Option('from-root',
1801
2444
                   help='Print paths relative to the root of the branch.'),
1802
2445
            Option('unknown', help='Print unknown files.'),
1813
2456
            ]
1814
2457
    @display_command
1815
2458
    def run(self, revision=None, verbose=False,
1816
 
            non_recursive=False, from_root=False,
 
2459
            recursive=False, from_root=False,
1817
2460
            unknown=False, versioned=False, ignored=False,
1818
2461
            null=False, kind=None, show_ids=False, path=None):
1819
2462
 
1828
2471
 
1829
2472
        if path is None:
1830
2473
            fs_path = '.'
1831
 
            prefix = ''
1832
2474
        else:
1833
2475
            if from_root:
1834
2476
                raise errors.BzrCommandError('cannot specify both --from-root'
1835
2477
                                             ' and PATH')
1836
2478
            fs_path = path
1837
 
            prefix = path
1838
2479
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1839
2480
            fs_path)
 
2481
 
 
2482
        # Calculate the prefix to use
 
2483
        prefix = None
1840
2484
        if from_root:
1841
 
            relpath = u''
1842
 
        elif relpath:
1843
 
            relpath += '/'
1844
 
        if revision is not None:
1845
 
            tree = branch.repository.revision_tree(
1846
 
                revision[0].as_revision_id(branch))
1847
 
        elif tree is None:
1848
 
            tree = branch.basis_tree()
 
2485
            if relpath:
 
2486
                prefix = relpath + '/'
 
2487
        elif fs_path != '.':
 
2488
            prefix = fs_path + '/'
 
2489
 
 
2490
        if revision is not None or tree is None:
 
2491
            tree = _get_one_revision_tree('ls', revision, branch=branch)
 
2492
 
 
2493
        apply_view = False
 
2494
        if isinstance(tree, WorkingTree) and tree.supports_views():
 
2495
            view_files = tree.views.lookup_view()
 
2496
            if view_files:
 
2497
                apply_view = True
 
2498
                view_str = views.view_display_str(view_files)
 
2499
                note("Ignoring files outside view. View is %s" % view_str)
1849
2500
 
1850
2501
        tree.lock_read()
1851
2502
        try:
1852
 
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1853
 
                if fp.startswith(relpath):
1854
 
                    fp = osutils.pathjoin(prefix, fp[len(relpath):])
1855
 
                    if non_recursive and '/' in fp:
1856
 
                        continue
1857
 
                    if not all and not selection[fc]:
1858
 
                        continue
1859
 
                    if kind is not None and fkind != kind:
1860
 
                        continue
1861
 
                    if verbose:
1862
 
                        kindch = entry.kind_character()
1863
 
                        outstring = '%-8s %s%s' % (fc, fp, kindch)
1864
 
                        if show_ids and fid is not None:
1865
 
                            outstring = "%-50s %s" % (outstring, fid)
1866
 
                        self.outf.write(outstring + '\n')
1867
 
                    elif null:
1868
 
                        self.outf.write(fp + '\0')
1869
 
                        if show_ids:
1870
 
                            if fid is not None:
1871
 
                                self.outf.write(fid)
1872
 
                            self.outf.write('\0')
1873
 
                        self.outf.flush()
1874
 
                    else:
 
2503
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
2504
                from_dir=relpath, recursive=recursive):
 
2505
                # Apply additional masking
 
2506
                if not all and not selection[fc]:
 
2507
                    continue
 
2508
                if kind is not None and fkind != kind:
 
2509
                    continue
 
2510
                if apply_view:
 
2511
                    try:
 
2512
                        if relpath:
 
2513
                            fullpath = osutils.pathjoin(relpath, fp)
 
2514
                        else:
 
2515
                            fullpath = fp
 
2516
                        views.check_path_in_view(tree, fullpath)
 
2517
                    except errors.FileOutsideView:
 
2518
                        continue
 
2519
 
 
2520
                # Output the entry
 
2521
                if prefix:
 
2522
                    fp = osutils.pathjoin(prefix, fp)
 
2523
                kindch = entry.kind_character()
 
2524
                outstring = fp + kindch
 
2525
                ui.ui_factory.clear_term()
 
2526
                if verbose:
 
2527
                    outstring = '%-8s %s' % (fc, outstring)
 
2528
                    if show_ids and fid is not None:
 
2529
                        outstring = "%-50s %s" % (outstring, fid)
 
2530
                    self.outf.write(outstring + '\n')
 
2531
                elif null:
 
2532
                    self.outf.write(fp + '\0')
 
2533
                    if show_ids:
 
2534
                        if fid is not None:
 
2535
                            self.outf.write(fid)
 
2536
                        self.outf.write('\0')
 
2537
                    self.outf.flush()
 
2538
                else:
 
2539
                    if show_ids:
1875
2540
                        if fid is not None:
1876
2541
                            my_id = fid
1877
2542
                        else:
1878
2543
                            my_id = ''
1879
 
                        if show_ids:
1880
 
                            self.outf.write('%-50s %s\n' % (fp, my_id))
1881
 
                        else:
1882
 
                            self.outf.write(fp + '\n')
 
2544
                        self.outf.write('%-50s %s\n' % (outstring, my_id))
 
2545
                    else:
 
2546
                        self.outf.write(outstring + '\n')
1883
2547
        finally:
1884
2548
            tree.unlock()
1885
2549
 
1907
2571
    using this command or directly by using an editor, be sure to commit
1908
2572
    it.
1909
2573
 
1910
 
    Note: ignore patterns containing shell wildcards must be quoted from 
 
2574
    Note: ignore patterns containing shell wildcards must be quoted from
1911
2575
    the shell on Unix.
1912
2576
 
1913
2577
    :Examples:
1938
2602
        Option('old-default-rules',
1939
2603
               help='Write out the ignore rules bzr < 0.9 always used.')
1940
2604
        ]
1941
 
    
 
2605
 
1942
2606
    def run(self, name_pattern_list=None, old_default_rules=None):
1943
2607
        from bzrlib import ignores
1944
2608
        if old_default_rules is not None:
1949
2613
        if not name_pattern_list:
1950
2614
            raise errors.BzrCommandError("ignore requires at least one "
1951
2615
                                  "NAME_PATTERN or --old-default-rules")
1952
 
        name_pattern_list = [globbing.normalize_pattern(p) 
 
2616
        name_pattern_list = [globbing.normalize_pattern(p)
1953
2617
                             for p in name_pattern_list]
1954
2618
        for name_pattern in name_pattern_list:
1955
 
            if (name_pattern[0] == '/' or 
 
2619
            if (name_pattern[0] == '/' or
1956
2620
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
1957
2621
                raise errors.BzrCommandError(
1958
2622
                    "NAME_PATTERN should not be an absolute path")
1970
2634
        tree.unlock()
1971
2635
        if len(matches) > 0:
1972
2636
            print "Warning: the following files are version controlled and" \
1973
 
                  " match your ignore pattern:\n%s" % ("\n".join(matches),)
 
2637
                  " match your ignore pattern:\n%s" \
 
2638
                  "\nThese files will continue to be version controlled" \
 
2639
                  " unless you 'bzr remove' them." % ("\n".join(matches),)
1974
2640
 
1975
2641
 
1976
2642
class cmd_ignored(Command):
2010
2676
    """
2011
2677
    hidden = True
2012
2678
    takes_args = ['revno']
2013
 
    
 
2679
 
2014
2680
    @display_command
2015
2681
    def run(self, revno):
2016
2682
        try:
2055
2721
               help="Type of file to export to.",
2056
2722
               type=unicode),
2057
2723
        'revision',
 
2724
        Option('filters', help='Apply content filters to export the '
 
2725
                'convenient form.'),
2058
2726
        Option('root',
2059
2727
               type=str,
2060
2728
               help="Name of the root directory inside the exported file."),
2061
2729
        ]
2062
2730
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2063
 
        root=None):
 
2731
        root=None, filters=False):
2064
2732
        from bzrlib.export import export
2065
2733
 
2066
2734
        if branch_or_subdir is None:
2069
2737
            subdir = None
2070
2738
        else:
2071
2739
            b, subdir = Branch.open_containing(branch_or_subdir)
2072
 
            
2073
 
        if revision is None:
2074
 
            # should be tree.last_revision  FIXME
2075
 
            rev_id = b.last_revision()
2076
 
        else:
2077
 
            if len(revision) != 1:
2078
 
                raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2079
 
            rev_id = revision[0].as_revision_id(b)
2080
 
        t = b.repository.revision_tree(rev_id)
 
2740
            tree = None
 
2741
 
 
2742
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2081
2743
        try:
2082
 
            export(t, dest, format, root, subdir)
 
2744
            export(rev_tree, dest, format, root, subdir, filtered=filters)
2083
2745
        except errors.NoSuchExportFormat, e:
2084
2746
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2085
2747
 
2090
2752
    If no revision is nominated, the last revision is used.
2091
2753
 
2092
2754
    Note: Take care to redirect standard output when using this command on a
2093
 
    binary file. 
 
2755
    binary file.
2094
2756
    """
2095
2757
 
2096
2758
    _see_also = ['ls']
2097
2759
    takes_options = [
2098
2760
        Option('name-from-revision', help='The path name in the old tree.'),
 
2761
        Option('filters', help='Apply content filters to display the '
 
2762
                'convenience form.'),
2099
2763
        'revision',
2100
2764
        ]
2101
2765
    takes_args = ['filename']
2102
2766
    encoding_type = 'exact'
2103
2767
 
2104
2768
    @display_command
2105
 
    def run(self, filename, revision=None, name_from_revision=False):
 
2769
    def run(self, filename, revision=None, name_from_revision=False,
 
2770
            filters=False):
2106
2771
        if revision is not None and len(revision) != 1:
2107
2772
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2108
2773
                                         " one revision specifier")
2111
2776
        branch.lock_read()
2112
2777
        try:
2113
2778
            return self._run(tree, branch, relpath, filename, revision,
2114
 
                             name_from_revision)
 
2779
                             name_from_revision, filters)
2115
2780
        finally:
2116
2781
            branch.unlock()
2117
2782
 
2118
 
    def _run(self, tree, b, relpath, filename, revision, name_from_revision):
 
2783
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
 
2784
        filtered):
2119
2785
        if tree is None:
2120
2786
            tree = b.basis_tree()
2121
 
        if revision is None:
2122
 
            revision_id = b.last_revision()
2123
 
        else:
2124
 
            revision_id = revision[0].as_revision_id(b)
 
2787
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2125
2788
 
2126
 
        cur_file_id = tree.path2id(relpath)
2127
 
        rev_tree = b.repository.revision_tree(revision_id)
2128
2789
        old_file_id = rev_tree.path2id(relpath)
2129
 
        
 
2790
 
2130
2791
        if name_from_revision:
 
2792
            # Try in revision if requested
2131
2793
            if old_file_id is None:
2132
 
                raise errors.BzrCommandError("%r is not present in revision %s"
2133
 
                                                % (filename, revision_id))
 
2794
                raise errors.BzrCommandError(
 
2795
                    "%r is not present in revision %s" % (
 
2796
                        filename, rev_tree.get_revision_id()))
2134
2797
            else:
2135
2798
                content = rev_tree.get_file_text(old_file_id)
2136
 
        elif cur_file_id is not None:
2137
 
            content = rev_tree.get_file_text(cur_file_id)
2138
 
        elif old_file_id is not None:
2139
 
            content = rev_tree.get_file_text(old_file_id)
2140
 
        else:
2141
 
            raise errors.BzrCommandError("%r is not present in revision %s" %
2142
 
                                         (filename, revision_id))
2143
 
        self.outf.write(content)
 
2799
        else:
 
2800
            cur_file_id = tree.path2id(relpath)
 
2801
            found = False
 
2802
            if cur_file_id is not None:
 
2803
                # Then try with the actual file id
 
2804
                try:
 
2805
                    content = rev_tree.get_file_text(cur_file_id)
 
2806
                    found = True
 
2807
                except errors.NoSuchId:
 
2808
                    # The actual file id didn't exist at that time
 
2809
                    pass
 
2810
            if not found and old_file_id is not None:
 
2811
                # Finally try with the old file id
 
2812
                content = rev_tree.get_file_text(old_file_id)
 
2813
                found = True
 
2814
            if not found:
 
2815
                # Can't be found anywhere
 
2816
                raise errors.BzrCommandError(
 
2817
                    "%r is not present in revision %s" % (
 
2818
                        filename, rev_tree.get_revision_id()))
 
2819
        if filtered:
 
2820
            from bzrlib.filters import (
 
2821
                ContentFilterContext,
 
2822
                filtered_output_bytes,
 
2823
                )
 
2824
            filters = rev_tree._content_filter_stack(relpath)
 
2825
            chunks = content.splitlines(True)
 
2826
            content = filtered_output_bytes(chunks, filters,
 
2827
                ContentFilterContext(relpath, rev_tree))
 
2828
            self.outf.writelines(content)
 
2829
        else:
 
2830
            self.outf.write(content)
2144
2831
 
2145
2832
 
2146
2833
class cmd_local_time_offset(Command):
2147
2834
    """Show the offset in seconds from GMT to local time."""
2148
 
    hidden = True    
 
2835
    hidden = True
2149
2836
    @display_command
2150
2837
    def run(self):
2151
2838
        print osutils.local_time_offset()
2154
2841
 
2155
2842
class cmd_commit(Command):
2156
2843
    """Commit changes into a new revision.
2157
 
    
2158
 
    If no arguments are given, the entire tree is committed.
2159
 
 
2160
 
    If selected files are specified, only changes to those files are
2161
 
    committed.  If a directory is specified then the directory and everything 
2162
 
    within it is committed.
2163
 
 
2164
 
    When excludes are given, they take precedence over selected files.
2165
 
    For example, too commit only changes within foo, but not changes within
2166
 
    foo/bar::
2167
 
 
2168
 
      bzr commit foo -x foo/bar
2169
 
 
2170
 
    If author of the change is not the same person as the committer, you can
2171
 
    specify the author's name using the --author option. The name should be
2172
 
    in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2173
 
 
2174
 
    A selected-file commit may fail in some cases where the committed
2175
 
    tree would be invalid. Consider::
2176
 
 
2177
 
      bzr init foo
2178
 
      mkdir foo/bar
2179
 
      bzr add foo/bar
2180
 
      bzr commit foo -m "committing foo"
2181
 
      bzr mv foo/bar foo/baz
2182
 
      mkdir foo/bar
2183
 
      bzr add foo/bar
2184
 
      bzr commit foo/bar -m "committing bar but not baz"
2185
 
 
2186
 
    In the example above, the last commit will fail by design. This gives
2187
 
    the user the opportunity to decide whether they want to commit the
2188
 
    rename at the same time, separately first, or not at all. (As a general
2189
 
    rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2190
 
 
2191
 
    Note: A selected-file commit after a merge is not yet supported.
 
2844
 
 
2845
    An explanatory message needs to be given for each commit. This is
 
2846
    often done by using the --message option (getting the message from the
 
2847
    command line) or by using the --file option (getting the message from
 
2848
    a file). If neither of these options is given, an editor is opened for
 
2849
    the user to enter the message. To see the changed files in the
 
2850
    boilerplate text loaded into the editor, use the --show-diff option.
 
2851
 
 
2852
    By default, the entire tree is committed and the person doing the
 
2853
    commit is assumed to be the author. These defaults can be overridden
 
2854
    as explained below.
 
2855
 
 
2856
    :Selective commits:
 
2857
 
 
2858
      If selected files are specified, only changes to those files are
 
2859
      committed.  If a directory is specified then the directory and
 
2860
      everything within it is committed.
 
2861
  
 
2862
      When excludes are given, they take precedence over selected files.
 
2863
      For example, to commit only changes within foo, but not changes
 
2864
      within foo/bar::
 
2865
  
 
2866
        bzr commit foo -x foo/bar
 
2867
  
 
2868
      A selective commit after a merge is not yet supported.
 
2869
 
 
2870
    :Custom authors:
 
2871
 
 
2872
      If the author of the change is not the same person as the committer,
 
2873
      you can specify the author's name using the --author option. The
 
2874
      name should be in the same format as a committer-id, e.g.
 
2875
      "John Doe <jdoe@example.com>". If there is more than one author of
 
2876
      the change you can specify the option multiple times, once for each
 
2877
      author.
 
2878
  
 
2879
    :Checks:
 
2880
 
 
2881
      A common mistake is to forget to add a new file or directory before
 
2882
      running the commit command. The --strict option checks for unknown
 
2883
      files and aborts the commit if any are found. More advanced pre-commit
 
2884
      checks can be implemented by defining hooks. See ``bzr help hooks``
 
2885
      for details.
 
2886
 
 
2887
    :Things to note:
 
2888
 
 
2889
      If you accidentially commit the wrong changes or make a spelling
 
2890
      mistake in the commit message say, you can use the uncommit command
 
2891
      to undo it. See ``bzr help uncommit`` for details.
 
2892
 
 
2893
      Hooks can also be configured to run after a commit. This allows you
 
2894
      to trigger updates to external systems like bug trackers. The --fixes
 
2895
      option can be used to record the association between a revision and
 
2896
      one or more bugs. See ``bzr help bugs`` for details.
 
2897
 
 
2898
      A selective commit may fail in some cases where the committed
 
2899
      tree would be invalid. Consider::
 
2900
  
 
2901
        bzr init foo
 
2902
        mkdir foo/bar
 
2903
        bzr add foo/bar
 
2904
        bzr commit foo -m "committing foo"
 
2905
        bzr mv foo/bar foo/baz
 
2906
        mkdir foo/bar
 
2907
        bzr add foo/bar
 
2908
        bzr commit foo/bar -m "committing bar but not baz"
 
2909
  
 
2910
      In the example above, the last commit will fail by design. This gives
 
2911
      the user the opportunity to decide whether they want to commit the
 
2912
      rename at the same time, separately first, or not at all. (As a general
 
2913
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2192
2914
    """
2193
2915
    # TODO: Run hooks on tree to-be-committed, and after commit.
2194
2916
 
2199
2921
 
2200
2922
    # XXX: verbose currently does nothing
2201
2923
 
2202
 
    _see_also = ['bugs', 'uncommit']
 
2924
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
2203
2925
    takes_args = ['selected*']
2204
2926
    takes_options = [
2205
2927
            ListOption('exclude', type=str, short_name='x',
2218
2940
                    help="Refuse to commit if there are unknown "
2219
2941
                    "files in the working tree."),
2220
2942
             ListOption('fixes', type=str,
2221
 
                    help="Mark a bug as being fixed by this revision."),
2222
 
             Option('author', type=unicode,
 
2943
                    help="Mark a bug as being fixed by this revision "
 
2944
                         "(see \"bzr help bugs\")."),
 
2945
             ListOption('author', type=unicode,
2223
2946
                    help="Set the author's name, if it's different "
2224
2947
                         "from the committer."),
2225
2948
             Option('local',
2234
2957
             ]
2235
2958
    aliases = ['ci', 'checkin']
2236
2959
 
2237
 
    def _get_bug_fix_properties(self, fixes, branch):
2238
 
        properties = []
 
2960
    def _iter_bug_fix_urls(self, fixes, branch):
2239
2961
        # Configure the properties for bug fixing attributes.
2240
2962
        for fixed_bug in fixes:
2241
2963
            tokens = fixed_bug.split(':')
2242
2964
            if len(tokens) != 2:
2243
2965
                raise errors.BzrCommandError(
2244
 
                    "Invalid bug %s. Must be in the form of 'tag:id'. "
2245
 
                    "Commit refused." % fixed_bug)
 
2966
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
 
2967
                    "See \"bzr help bugs\" for more information on this "
 
2968
                    "feature.\nCommit refused." % fixed_bug)
2246
2969
            tag, bug_id = tokens
2247
2970
            try:
2248
 
                bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
 
2971
                yield bugtracker.get_bug_url(tag, branch, bug_id)
2249
2972
            except errors.UnknownBugTrackerAbbreviation:
2250
2973
                raise errors.BzrCommandError(
2251
2974
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
2252
 
            except errors.MalformedBugIdentifier:
 
2975
            except errors.MalformedBugIdentifier, e:
2253
2976
                raise errors.BzrCommandError(
2254
 
                    "Invalid bug identifier for %s. Commit refused."
2255
 
                    % fixed_bug)
2256
 
            properties.append('%s fixed' % bug_url)
2257
 
        return '\n'.join(properties)
 
2977
                    "%s\nCommit refused." % (str(e),))
2258
2978
 
2259
2979
    def run(self, message=None, file=None, verbose=False, selected_list=None,
2260
2980
            unchanged=False, strict=False, local=False, fixes=None,
2266
2986
        )
2267
2987
        from bzrlib.msgeditor import (
2268
2988
            edit_commit_message_encoded,
 
2989
            generate_commit_message_template,
2269
2990
            make_commit_message_template_encoded
2270
2991
        )
2271
2992
 
2272
2993
        # TODO: Need a blackbox test for invoking the external editor; may be
2273
2994
        # slightly problematic to run this cross-platform.
2274
2995
 
2275
 
        # TODO: do more checks that the commit will succeed before 
 
2996
        # TODO: do more checks that the commit will succeed before
2276
2997
        # spending the user's valuable time typing a commit message.
2277
2998
 
2278
2999
        properties = {}
2286
3007
 
2287
3008
        if fixes is None:
2288
3009
            fixes = []
2289
 
        bug_property = self._get_bug_fix_properties(fixes, tree.branch)
 
3010
        bug_property = bugtracker.encode_fixes_bug_urls(
 
3011
            self._iter_bug_fix_urls(fixes, tree.branch))
2290
3012
        if bug_property:
2291
3013
            properties['bugs'] = bug_property
2292
3014
 
2299
3021
            if my_message is None and not file:
2300
3022
                t = make_commit_message_template_encoded(tree,
2301
3023
                        selected_list, diff=show_diff,
2302
 
                        output_encoding=bzrlib.user_encoding)
2303
 
                my_message = edit_commit_message_encoded(t)
 
3024
                        output_encoding=osutils.get_user_encoding())
 
3025
                start_message = generate_commit_message_template(commit_obj)
 
3026
                my_message = edit_commit_message_encoded(t,
 
3027
                    start_message=start_message)
2304
3028
                if my_message is None:
2305
3029
                    raise errors.BzrCommandError("please specify a commit"
2306
3030
                        " message with either --message or --file")
2309
3033
                    "please specify either --message or --file")
2310
3034
            if file:
2311
3035
                my_message = codecs.open(file, 'rt',
2312
 
                                         bzrlib.user_encoding).read()
 
3036
                                         osutils.get_user_encoding()).read()
2313
3037
            if my_message == "":
2314
3038
                raise errors.BzrCommandError("empty commit message specified")
2315
3039
            return my_message
2316
3040
 
 
3041
        # The API permits a commit with a filter of [] to mean 'select nothing'
 
3042
        # but the command line should not do that.
 
3043
        if not selected_list:
 
3044
            selected_list = None
2317
3045
        try:
2318
3046
            tree.commit(message_callback=get_message,
2319
3047
                        specific_files=selected_list,
2320
3048
                        allow_pointless=unchanged, strict=strict, local=local,
2321
3049
                        reporter=None, verbose=verbose, revprops=properties,
2322
 
                        author=author,
 
3050
                        authors=author,
2323
3051
                        exclude=safe_relpath_files(tree, exclude))
2324
3052
        except PointlessCommit:
2325
3053
            # FIXME: This should really happen before the file is read in;
2326
3054
            # perhaps prepare the commit; get the message; then actually commit
2327
 
            raise errors.BzrCommandError("no changes to commit."
2328
 
                              " use --unchanged to commit anyhow")
 
3055
            raise errors.BzrCommandError("No changes to commit."
 
3056
                              " Use --unchanged to commit anyhow.")
2329
3057
        except ConflictsInTree:
2330
3058
            raise errors.BzrCommandError('Conflicts detected in working '
2331
3059
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
2349
3077
    The working tree and branch checks will only give output if a problem is
2350
3078
    detected. The output fields of the repository check are:
2351
3079
 
2352
 
        revisions: This is just the number of revisions checked.  It doesn't
2353
 
            indicate a problem.
2354
 
        versionedfiles: This is just the number of versionedfiles checked.  It
2355
 
            doesn't indicate a problem.
2356
 
        unreferenced ancestors: Texts that are ancestors of other texts, but
2357
 
            are not properly referenced by the revision ancestry.  This is a
2358
 
            subtle problem that Bazaar can work around.
2359
 
        unique file texts: This is the total number of unique file contents
2360
 
            seen in the checked revisions.  It does not indicate a problem.
2361
 
        repeated file texts: This is the total number of repeated texts seen
2362
 
            in the checked revisions.  Texts can be repeated when their file
2363
 
            entries are modified, but the file contents are not.  It does not
2364
 
            indicate a problem.
 
3080
    revisions
 
3081
        This is just the number of revisions checked.  It doesn't
 
3082
        indicate a problem.
 
3083
 
 
3084
    versionedfiles
 
3085
        This is just the number of versionedfiles checked.  It
 
3086
        doesn't indicate a problem.
 
3087
 
 
3088
    unreferenced ancestors
 
3089
        Texts that are ancestors of other texts, but
 
3090
        are not properly referenced by the revision ancestry.  This is a
 
3091
        subtle problem that Bazaar can work around.
 
3092
 
 
3093
    unique file texts
 
3094
        This is the total number of unique file contents
 
3095
        seen in the checked revisions.  It does not indicate a problem.
 
3096
 
 
3097
    repeated file texts
 
3098
        This is the total number of repeated texts seen
 
3099
        in the checked revisions.  Texts can be repeated when their file
 
3100
        entries are modified, but the file contents are not.  It does not
 
3101
        indicate a problem.
2365
3102
 
2366
3103
    If no restrictions are specified, all Bazaar data that is found at the given
2367
3104
    location will be checked.
2415
3152
                    RegistryOption('format',
2416
3153
                        help='Upgrade to a specific format.  See "bzr help'
2417
3154
                             ' formats" for details.',
2418
 
                        registry=bzrdir.format_registry,
2419
 
                        converter=bzrdir.format_registry.make_bzrdir,
 
3155
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3156
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2420
3157
                        value_switches=True, title='Branch format'),
2421
3158
                    ]
2422
3159
 
2423
3160
    def run(self, url='.', format=None):
2424
3161
        from bzrlib.upgrade import upgrade
2425
 
        if format is None:
2426
 
            format = bzrdir.format_registry.make_bzrdir('default')
2427
3162
        upgrade(url, format)
2428
3163
 
2429
3164
 
2430
3165
class cmd_whoami(Command):
2431
3166
    """Show or set bzr user id.
2432
 
    
 
3167
 
2433
3168
    :Examples:
2434
3169
        Show the email of the current user::
2435
3170
 
2447
3182
                    ]
2448
3183
    takes_args = ['name?']
2449
3184
    encoding_type = 'replace'
2450
 
    
 
3185
 
2451
3186
    @display_command
2452
3187
    def run(self, email=False, branch=False, name=None):
2453
3188
        if name is None:
2468
3203
        except errors.NoEmailInUsername, e:
2469
3204
            warning('"%s" does not seem to contain an email address.  '
2470
3205
                    'This is allowed, but not recommended.', name)
2471
 
        
 
3206
 
2472
3207
        # use global config unless --branch given
2473
3208
        if branch:
2474
3209
            c = Branch.open_containing('.')[0].get_config()
2478
3213
 
2479
3214
 
2480
3215
class cmd_nick(Command):
2481
 
    """Print or set the branch nickname.  
2482
 
 
2483
 
    If unset, the tree root directory name is used as the nickname
2484
 
    To print the current nickname, execute with no argument.  
 
3216
    """Print or set the branch nickname.
 
3217
 
 
3218
    If unset, the tree root directory name is used as the nickname.
 
3219
    To print the current nickname, execute with no argument.
 
3220
 
 
3221
    Bound branches use the nickname of its master branch unless it is set
 
3222
    locally.
2485
3223
    """
2486
3224
 
2487
3225
    _see_also = ['info']
2570
3308
 
2571
3309
class cmd_selftest(Command):
2572
3310
    """Run internal test suite.
2573
 
    
 
3311
 
2574
3312
    If arguments are given, they are regular expressions that say which tests
2575
3313
    should run.  Tests matching any expression are run, and other tests are
2576
3314
    not run.
2599
3337
    modified by plugins will not be tested, and tests provided by plugins will
2600
3338
    not be run.
2601
3339
 
2602
 
    Tests that need working space on disk use a common temporary directory, 
 
3340
    Tests that need working space on disk use a common temporary directory,
2603
3341
    typically inside $TMPDIR or /tmp.
2604
3342
 
2605
3343
    :Examples:
2644
3382
                     Option('lsprof-timed',
2645
3383
                            help='Generate lsprof output for benchmarked'
2646
3384
                                 ' sections of code.'),
 
3385
                     Option('lsprof-tests',
 
3386
                            help='Generate lsprof output for each test.'),
2647
3387
                     Option('cache-dir', type=str,
2648
3388
                            help='Cache intermediate benchmark output in this '
2649
3389
                                 'directory.'),
2653
3393
                            ),
2654
3394
                     Option('list-only',
2655
3395
                            help='List the tests instead of running them.'),
 
3396
                     RegistryOption('parallel',
 
3397
                        help="Run the test suite in parallel.",
 
3398
                        lazy_registry=('bzrlib.tests', 'parallel_registry'),
 
3399
                        value_switches=False,
 
3400
                        ),
2656
3401
                     Option('randomize', type=str, argname="SEED",
2657
3402
                            help='Randomize the order of tests using the given'
2658
3403
                                 ' seed or "now" for the current time.'),
2660
3405
                            short_name='x',
2661
3406
                            help='Exclude tests that match this regular'
2662
3407
                                 ' expression.'),
 
3408
                     Option('subunit',
 
3409
                        help='Output test progress via subunit.'),
2663
3410
                     Option('strict', help='Fail on missing dependencies or '
2664
3411
                            'known failures.'),
2665
3412
                     Option('load-list', type=str, argname='TESTLISTFILE',
2673
3420
                     ]
2674
3421
    encoding_type = 'replace'
2675
3422
 
 
3423
    def __init__(self):
 
3424
        Command.__init__(self)
 
3425
        self.additional_selftest_args = {}
 
3426
 
2676
3427
    def run(self, testspecs_list=None, verbose=False, one=False,
2677
3428
            transport=None, benchmark=None,
2678
3429
            lsprof_timed=None, cache_dir=None,
2679
3430
            first=False, list_only=False,
2680
3431
            randomize=None, exclude=None, strict=False,
2681
 
            load_list=None, debugflag=None, starting_with=None):
2682
 
        import bzrlib.ui
 
3432
            load_list=None, debugflag=None, starting_with=None, subunit=False,
 
3433
            parallel=None, lsprof_tests=False):
2683
3434
        from bzrlib.tests import selftest
2684
3435
        import bzrlib.benchmarks as benchmarks
2685
3436
        from bzrlib.benchmarks import tree_creator
2689
3440
 
2690
3441
        if cache_dir is not None:
2691
3442
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2692
 
        if not list_only:
2693
 
            print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2694
 
            print '   %s (%s python%s)' % (
2695
 
                    bzrlib.__path__[0],
2696
 
                    bzrlib.version_string,
2697
 
                    bzrlib._format_version_tuple(sys.version_info),
2698
 
                    )
2699
 
        print
2700
3443
        if testspecs_list is not None:
2701
3444
            pattern = '|'.join(testspecs_list)
2702
3445
        else:
2703
3446
            pattern = ".*"
 
3447
        if subunit:
 
3448
            try:
 
3449
                from bzrlib.tests import SubUnitBzrRunner
 
3450
            except ImportError:
 
3451
                raise errors.BzrCommandError("subunit not available. subunit "
 
3452
                    "needs to be installed to use --subunit.")
 
3453
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
 
3454
        if parallel:
 
3455
            self.additional_selftest_args.setdefault(
 
3456
                'suite_decorators', []).append(parallel)
2704
3457
        if benchmark:
2705
3458
            test_suite_factory = benchmarks.test_suite
2706
3459
            # Unless user explicitly asks for quiet, be verbose in benchmarks
2711
3464
            test_suite_factory = None
2712
3465
            benchfile = None
2713
3466
        try:
2714
 
            result = selftest(verbose=verbose,
2715
 
                              pattern=pattern,
2716
 
                              stop_on_failure=one,
2717
 
                              transport=transport,
2718
 
                              test_suite_factory=test_suite_factory,
2719
 
                              lsprof_timed=lsprof_timed,
2720
 
                              bench_history=benchfile,
2721
 
                              matching_tests_first=first,
2722
 
                              list_only=list_only,
2723
 
                              random_seed=randomize,
2724
 
                              exclude_pattern=exclude,
2725
 
                              strict=strict,
2726
 
                              load_list=load_list,
2727
 
                              debug_flags=debugflag,
2728
 
                              starting_with=starting_with,
2729
 
                              )
 
3467
            selftest_kwargs = {"verbose": verbose,
 
3468
                              "pattern": pattern,
 
3469
                              "stop_on_failure": one,
 
3470
                              "transport": transport,
 
3471
                              "test_suite_factory": test_suite_factory,
 
3472
                              "lsprof_timed": lsprof_timed,
 
3473
                              "lsprof_tests": lsprof_tests,
 
3474
                              "bench_history": benchfile,
 
3475
                              "matching_tests_first": first,
 
3476
                              "list_only": list_only,
 
3477
                              "random_seed": randomize,
 
3478
                              "exclude_pattern": exclude,
 
3479
                              "strict": strict,
 
3480
                              "load_list": load_list,
 
3481
                              "debug_flags": debugflag,
 
3482
                              "starting_with": starting_with
 
3483
                              }
 
3484
            selftest_kwargs.update(self.additional_selftest_args)
 
3485
            result = selftest(**selftest_kwargs)
2730
3486
        finally:
2731
3487
            if benchfile is not None:
2732
3488
                benchfile.close()
2733
 
        if result:
2734
 
            note('tests passed')
2735
 
        else:
2736
 
            note('tests failed')
2737
3489
        return int(not result)
2738
3490
 
2739
3491
 
2770
3522
    #       merging only part of the history.
2771
3523
    takes_args = ['branch', 'other']
2772
3524
    hidden = True
2773
 
    
 
3525
 
2774
3526
    @display_command
2775
3527
    def run(self, branch, other):
2776
3528
        from bzrlib.revision import ensure_null
2777
 
        
 
3529
 
2778
3530
        branch1 = Branch.open_containing(branch)[0]
2779
3531
        branch2 = Branch.open_containing(other)[0]
2780
3532
        branch1.lock_read()
2796
3548
 
2797
3549
class cmd_merge(Command):
2798
3550
    """Perform a three-way merge.
2799
 
    
 
3551
 
2800
3552
    The source of the merge can be specified either in the form of a branch,
2801
3553
    or in the form of a path to a file containing a merge directive generated
2802
3554
    with bzr send. If neither is specified, the default is the upstream branch
2812
3564
    By default, bzr will try to merge in all new work from the other
2813
3565
    branch, automatically determining an appropriate base.  If this
2814
3566
    fails, you may need to give an explicit base.
2815
 
    
 
3567
 
2816
3568
    Merge will do its best to combine the changes in two branches, but there
2817
3569
    are some kinds of problems only a human can fix.  When it encounters those,
2818
3570
    it will mark a conflict.  A conflict means that you need to fix something,
2828
3580
    The results of the merge are placed into the destination working
2829
3581
    directory, where they can be reviewed (with bzr diff), tested, and then
2830
3582
    committed to record the result of the merge.
2831
 
    
 
3583
 
2832
3584
    merge refuses to run if there are any uncommitted changes, unless
2833
3585
    --force is given.
2834
3586
 
 
3587
    To select only some changes to merge, use "merge -i", which will prompt
 
3588
    you to apply each diff hunk and file change, similar to "shelve".
 
3589
 
2835
3590
    :Examples:
2836
3591
        To merge the latest revision from bzr.dev::
2837
3592
 
2845
3600
 
2846
3601
            bzr merge -r 81..82 ../bzr.dev
2847
3602
 
2848
 
        To apply a merge directive contained in in /tmp/merge:
 
3603
        To apply a merge directive contained in /tmp/merge:
2849
3604
 
2850
3605
            bzr merge /tmp/merge
2851
3606
    """
2852
3607
 
2853
3608
    encoding_type = 'exact'
2854
 
    _see_also = ['update', 'remerge', 'status-flags']
 
3609
    _see_also = ['update', 'remerge', 'status-flags', 'send']
2855
3610
    takes_args = ['location?']
2856
3611
    takes_options = [
2857
3612
        'change',
2875
3630
               short_name='d',
2876
3631
               type=unicode,
2877
3632
               ),
2878
 
        Option('preview', help='Instead of merging, show a diff of the merge.')
 
3633
        Option('preview', help='Instead of merging, show a diff of the'
 
3634
               ' merge.'),
 
3635
        Option('interactive', help='Select changes interactively.',
 
3636
            short_name='i')
2879
3637
    ]
2880
3638
 
2881
3639
    def run(self, location=None, revision=None, force=False,
2882
 
            merge_type=None, show_base=False, reprocess=False, remember=False,
 
3640
            merge_type=None, show_base=False, reprocess=None, remember=False,
2883
3641
            uncommitted=False, pull=False,
2884
3642
            directory=None,
2885
3643
            preview=False,
 
3644
            interactive=False,
2886
3645
            ):
2887
3646
        if merge_type is None:
2888
3647
            merge_type = _mod_merge.Merge3Merger
2893
3652
        allow_pending = True
2894
3653
        verified = 'inapplicable'
2895
3654
        tree = WorkingTree.open_containing(directory)[0]
 
3655
 
 
3656
        # die as quickly as possible if there are uncommitted changes
 
3657
        try:
 
3658
            basis_tree = tree.revision_tree(tree.last_revision())
 
3659
        except errors.NoSuchRevision:
 
3660
            basis_tree = tree.basis_tree()
 
3661
        if not force:
 
3662
            if tree.has_changes(basis_tree):
 
3663
                raise errors.UncommittedChanges(tree)
 
3664
 
 
3665
        view_info = _get_view_info_for_change_reporter(tree)
2896
3666
        change_reporter = delta._ChangeReporter(
2897
 
            unversioned_filter=tree.is_ignored)
 
3667
            unversioned_filter=tree.is_ignored, view_info=view_info)
2898
3668
        cleanups = []
2899
3669
        try:
2900
3670
            pb = ui.ui_factory.nested_progress_bar()
2922
3692
                if revision is not None and len(revision) > 0:
2923
3693
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
2924
3694
                        ' --revision at the same time.')
2925
 
                location = self._select_branch_location(tree, location)[0]
2926
 
                other_tree, other_path = WorkingTree.open_containing(location)
2927
 
                merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2928
 
                    pb)
 
3695
                merger = self.get_merger_from_uncommitted(tree, location, pb,
 
3696
                                                          cleanups)
2929
3697
                allow_pending = False
2930
 
                if other_path != '':
2931
 
                    merger.interesting_files = [other_path]
2932
3698
 
2933
3699
            if merger is None:
2934
3700
                merger, allow_pending = self._get_merger_from_branch(tree,
2950
3716
                                       merger.other_rev_id)
2951
3717
                    result.report(self.outf)
2952
3718
                    return 0
2953
 
            merger.check_basis(not force)
 
3719
            merger.check_basis(False)
2954
3720
            if preview:
2955
 
                return self._do_preview(merger)
 
3721
                return self._do_preview(merger, cleanups)
 
3722
            elif interactive:
 
3723
                return self._do_interactive(merger, cleanups)
2956
3724
            else:
2957
3725
                return self._do_merge(merger, change_reporter, allow_pending,
2958
3726
                                      verified)
2960
3728
            for cleanup in reversed(cleanups):
2961
3729
                cleanup()
2962
3730
 
2963
 
    def _do_preview(self, merger):
2964
 
        from bzrlib.diff import show_diff_trees
 
3731
    def _get_preview(self, merger, cleanups):
2965
3732
        tree_merger = merger.make_merger()
2966
3733
        tt = tree_merger.make_preview_transform()
2967
 
        try:
2968
 
            result_tree = tt.get_preview_tree()
2969
 
            show_diff_trees(merger.this_tree, result_tree, self.outf,
2970
 
                            old_label='', new_label='')
2971
 
        finally:
2972
 
            tt.finalize()
 
3734
        cleanups.append(tt.finalize)
 
3735
        result_tree = tt.get_preview_tree()
 
3736
        return result_tree
 
3737
 
 
3738
    def _do_preview(self, merger, cleanups):
 
3739
        from bzrlib.diff import show_diff_trees
 
3740
        result_tree = self._get_preview(merger, cleanups)
 
3741
        show_diff_trees(merger.this_tree, result_tree, self.outf,
 
3742
                        old_label='', new_label='')
2973
3743
 
2974
3744
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
2975
3745
        merger.change_reporter = change_reporter
2983
3753
        else:
2984
3754
            return 0
2985
3755
 
 
3756
    def _do_interactive(self, merger, cleanups):
 
3757
        """Perform an interactive merge.
 
3758
 
 
3759
        This works by generating a preview tree of the merge, then using
 
3760
        Shelver to selectively remove the differences between the working tree
 
3761
        and the preview tree.
 
3762
        """
 
3763
        from bzrlib import shelf_ui
 
3764
        result_tree = self._get_preview(merger, cleanups)
 
3765
        writer = bzrlib.option.diff_writer_registry.get()
 
3766
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
 
3767
                                   reporter=shelf_ui.ApplyReporter(),
 
3768
                                   diff_writer=writer(sys.stdout))
 
3769
        shelver.run()
 
3770
 
2986
3771
    def sanity_check_merger(self, merger):
2987
3772
        if (merger.show_base and
2988
3773
            not merger.merge_type is _mod_merge.Merge3Merger):
2989
3774
            raise errors.BzrCommandError("Show-base is not supported for this"
2990
3775
                                         " merge type. %s" % merger.merge_type)
 
3776
        if merger.reprocess is None:
 
3777
            if merger.show_base:
 
3778
                merger.reprocess = False
 
3779
            else:
 
3780
                # Use reprocess if the merger supports it
 
3781
                merger.reprocess = merger.merge_type.supports_reprocess
2991
3782
        if merger.reprocess and not merger.merge_type.supports_reprocess:
2992
3783
            raise errors.BzrCommandError("Conflict reduction is not supported"
2993
3784
                                         " for merge type %s." %
3017
3808
            base_branch, base_path = Branch.open_containing(base_loc,
3018
3809
                possible_transports)
3019
3810
        # Find the revision ids
3020
 
        if revision is None or len(revision) < 1 or revision[-1] is None:
 
3811
        other_revision_id = None
 
3812
        base_revision_id = None
 
3813
        if revision is not None:
 
3814
            if len(revision) >= 1:
 
3815
                other_revision_id = revision[-1].as_revision_id(other_branch)
 
3816
            if len(revision) == 2:
 
3817
                base_revision_id = revision[0].as_revision_id(base_branch)
 
3818
        if other_revision_id is None:
3021
3819
            other_revision_id = _mod_revision.ensure_null(
3022
3820
                other_branch.last_revision())
3023
 
        else:
3024
 
            other_revision_id = revision[-1].as_revision_id(other_branch)
3025
 
        if (revision is not None and len(revision) == 2
3026
 
            and revision[0] is not None):
3027
 
            base_revision_id = revision[0].as_revision_id(base_branch)
3028
 
        else:
3029
 
            base_revision_id = None
3030
3821
        # Remember where we merge from
3031
3822
        if ((remember or tree.branch.get_submit_branch() is None) and
3032
3823
             user_location is not None):
3041
3832
            allow_pending = True
3042
3833
        return merger, allow_pending
3043
3834
 
 
3835
    def get_merger_from_uncommitted(self, tree, location, pb, cleanups):
 
3836
        """Get a merger for uncommitted changes.
 
3837
 
 
3838
        :param tree: The tree the merger should apply to.
 
3839
        :param location: The location containing uncommitted changes.
 
3840
        :param pb: The progress bar to use for showing progress.
 
3841
        :param cleanups: A list of operations to perform to clean up the
 
3842
            temporary directories, unfinalized objects, etc.
 
3843
        """
 
3844
        location = self._select_branch_location(tree, location)[0]
 
3845
        other_tree, other_path = WorkingTree.open_containing(location)
 
3846
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
 
3847
        if other_path != '':
 
3848
            merger.interesting_files = [other_path]
 
3849
        return merger
 
3850
 
3044
3851
    def _select_branch_location(self, tree, user_location, revision=None,
3045
3852
                                index=None):
3046
3853
        """Select a branch location, according to possible inputs.
3093
3900
    """Redo a merge.
3094
3901
 
3095
3902
    Use this if you want to try a different merge technique while resolving
3096
 
    conflicts.  Some merge techniques are better than others, and remerge 
 
3903
    conflicts.  Some merge techniques are better than others, and remerge
3097
3904
    lets you try different ones on different files.
3098
3905
 
3099
3906
    The options for remerge have the same meaning and defaults as the ones for
3103
3910
    :Examples:
3104
3911
        Re-do the merge of all conflicted files, and show the base text in
3105
3912
        conflict regions, in addition to the usual THIS and OTHER texts::
3106
 
      
 
3913
 
3107
3914
            bzr remerge --show-base
3108
3915
 
3109
3916
        Re-do the merge of "foobar", using the weave merge algorithm, with
3110
3917
        additional processing to reduce the size of conflict regions::
3111
 
      
 
3918
 
3112
3919
            bzr remerge --merge-type weave --reprocess foobar
3113
3920
    """
3114
3921
    takes_args = ['file*']
3144
3951
                    interesting_ids.add(file_id)
3145
3952
                    if tree.kind(file_id) != "directory":
3146
3953
                        continue
3147
 
                    
 
3954
 
3148
3955
                    for name, ie in tree.inventory.iter_entries(file_id):
3149
3956
                        interesting_ids.add(ie.file_id)
3150
3957
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3199
4006
    merge instead.  For example, "merge . --revision -2..-3" will remove the
3200
4007
    changes introduced by -2, without affecting the changes introduced by -1.
3201
4008
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3202
 
    
 
4009
 
3203
4010
    By default, any files that have been manually changed will be backed up
3204
4011
    first.  (Files changed only by merge are not backed up.)  Backup files have
3205
4012
    '.~#~' appended to their name, where # is a number.
3234
4041
    def run(self, revision=None, no_backup=False, file_list=None,
3235
4042
            forget_merges=None):
3236
4043
        tree, file_list = tree_files(file_list)
3237
 
        if forget_merges:
3238
 
            tree.set_parent_ids(tree.get_parent_ids()[:1])
3239
 
        else:
3240
 
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4044
        tree.lock_write()
 
4045
        try:
 
4046
            if forget_merges:
 
4047
                tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4048
            else:
 
4049
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4050
        finally:
 
4051
            tree.unlock()
3241
4052
 
3242
4053
    @staticmethod
3243
4054
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3244
 
        if revision is None:
3245
 
            rev_id = tree.last_revision()
3246
 
        elif len(revision) != 1:
3247
 
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
3248
 
        else:
3249
 
            rev_id = revision[0].as_revision_id(tree.branch)
 
4055
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3250
4056
        pb = ui.ui_factory.nested_progress_bar()
3251
4057
        try:
3252
 
            tree.revert(file_list,
3253
 
                        tree.branch.repository.revision_tree(rev_id),
3254
 
                        not no_backup, pb, report_changes=True)
 
4058
            tree.revert(file_list, rev_tree, not no_backup, pb,
 
4059
                report_changes=True)
3255
4060
        finally:
3256
4061
            pb.finished()
3257
4062
 
3276
4081
            ]
3277
4082
    takes_args = ['topic?']
3278
4083
    aliases = ['?', '--help', '-?', '-h']
3279
 
    
 
4084
 
3280
4085
    @display_command
3281
4086
    def run(self, topic=None, long=False):
3282
4087
        import bzrlib.help
3293
4098
    takes_args = ['context?']
3294
4099
    aliases = ['s-c']
3295
4100
    hidden = True
3296
 
    
 
4101
 
3297
4102
    @display_command
3298
4103
    def run(self, context=None):
3299
4104
        import shellcomplete
3302
4107
 
3303
4108
class cmd_missing(Command):
3304
4109
    """Show unmerged/unpulled revisions between two branches.
3305
 
    
 
4110
 
3306
4111
    OTHER_BRANCH may be local or remote.
 
4112
 
 
4113
    To filter on a range of revisions, you can use the command -r begin..end
 
4114
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
4115
    also valid.
 
4116
 
 
4117
    :Examples:
 
4118
 
 
4119
        Determine the missing revisions between this and the branch at the
 
4120
        remembered pull location::
 
4121
 
 
4122
            bzr missing
 
4123
 
 
4124
        Determine the missing revisions between this and another branch::
 
4125
 
 
4126
            bzr missing http://server/branch
 
4127
 
 
4128
        Determine the missing revisions up to a specific revision on the other
 
4129
        branch::
 
4130
 
 
4131
            bzr missing -r ..-10
 
4132
 
 
4133
        Determine the missing revisions up to a specific revision on this
 
4134
        branch::
 
4135
 
 
4136
            bzr missing --my-revision ..-10
3307
4137
    """
3308
4138
 
3309
4139
    _see_also = ['merge', 'pull']
3310
4140
    takes_args = ['other_branch?']
3311
4141
    takes_options = [
3312
 
            Option('reverse', 'Reverse the order of revisions.'),
3313
 
            Option('mine-only',
3314
 
                   'Display changes in the local branch only.'),
3315
 
            Option('this' , 'Same as --mine-only.'),
3316
 
            Option('theirs-only',
3317
 
                   'Display changes in the remote branch only.'),
3318
 
            Option('other', 'Same as --theirs-only.'),
3319
 
            'log-format',
3320
 
            'show-ids',
3321
 
            'verbose'
3322
 
            ]
 
4142
        Option('reverse', 'Reverse the order of revisions.'),
 
4143
        Option('mine-only',
 
4144
               'Display changes in the local branch only.'),
 
4145
        Option('this' , 'Same as --mine-only.'),
 
4146
        Option('theirs-only',
 
4147
               'Display changes in the remote branch only.'),
 
4148
        Option('other', 'Same as --theirs-only.'),
 
4149
        'log-format',
 
4150
        'show-ids',
 
4151
        'verbose',
 
4152
        custom_help('revision',
 
4153
             help='Filter on other branch revisions (inclusive). '
 
4154
                'See "help revisionspec" for details.'),
 
4155
        Option('my-revision',
 
4156
            type=_parse_revision_str,
 
4157
            help='Filter on local branch revisions (inclusive). '
 
4158
                'See "help revisionspec" for details.'),
 
4159
        Option('include-merges',
 
4160
               'Show all revisions in addition to the mainline ones.'),
 
4161
        ]
3323
4162
    encoding_type = 'replace'
3324
4163
 
3325
4164
    @display_command
3326
4165
    def run(self, other_branch=None, reverse=False, mine_only=False,
3327
 
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
3328
 
            show_ids=False, verbose=False, this=False, other=False):
 
4166
            theirs_only=False,
 
4167
            log_format=None, long=False, short=False, line=False,
 
4168
            show_ids=False, verbose=False, this=False, other=False,
 
4169
            include_merges=False, revision=None, my_revision=None):
3329
4170
        from bzrlib.missing import find_unmerged, iter_log_revisions
 
4171
        def message(s):
 
4172
            if not is_quiet():
 
4173
                self.outf.write(s)
3330
4174
 
3331
4175
        if this:
3332
4176
            mine_only = this
3350
4194
                                             " or specified.")
3351
4195
            display_url = urlutils.unescape_for_display(parent,
3352
4196
                                                        self.outf.encoding)
3353
 
            self.outf.write("Using saved parent location: "
 
4197
            message("Using saved parent location: "
3354
4198
                    + display_url + "\n")
3355
4199
 
3356
4200
        remote_branch = Branch.open(other_branch)
3357
4201
        if remote_branch.base == local_branch.base:
3358
4202
            remote_branch = local_branch
 
4203
 
 
4204
        local_revid_range = _revision_range_to_revid_range(
 
4205
            _get_revision_range(my_revision, local_branch,
 
4206
                self.name()))
 
4207
 
 
4208
        remote_revid_range = _revision_range_to_revid_range(
 
4209
            _get_revision_range(revision,
 
4210
                remote_branch, self.name()))
 
4211
 
3359
4212
        local_branch.lock_read()
3360
4213
        try:
3361
4214
            remote_branch.lock_read()
3362
4215
            try:
3363
4216
                local_extra, remote_extra = find_unmerged(
3364
 
                    local_branch, remote_branch, restrict)
 
4217
                    local_branch, remote_branch, restrict,
 
4218
                    backward=not reverse,
 
4219
                    include_merges=include_merges,
 
4220
                    local_revid_range=local_revid_range,
 
4221
                    remote_revid_range=remote_revid_range)
3365
4222
 
3366
4223
                if log_format is None:
3367
4224
                    registry = log.log_formatter_registry
3369
4226
                lf = log_format(to_file=self.outf,
3370
4227
                                show_ids=show_ids,
3371
4228
                                show_timezone='original')
3372
 
                if reverse is False:
3373
 
                    if local_extra is not None:
3374
 
                        local_extra.reverse()
3375
 
                    if remote_extra is not None:
3376
 
                        remote_extra.reverse()
3377
4229
 
3378
4230
                status_code = 0
3379
4231
                if local_extra and not theirs_only:
3380
 
                    self.outf.write("You have %d extra revision(s):\n" %
3381
 
                                    len(local_extra))
 
4232
                    message("You have %d extra revision(s):\n" %
 
4233
                        len(local_extra))
3382
4234
                    for revision in iter_log_revisions(local_extra,
3383
4235
                                        local_branch.repository,
3384
4236
                                        verbose):
3390
4242
 
3391
4243
                if remote_extra and not mine_only:
3392
4244
                    if printed_local is True:
3393
 
                        self.outf.write("\n\n\n")
3394
 
                    self.outf.write("You are missing %d revision(s):\n" %
3395
 
                                    len(remote_extra))
 
4245
                        message("\n\n\n")
 
4246
                    message("You are missing %d revision(s):\n" %
 
4247
                        len(remote_extra))
3396
4248
                    for revision in iter_log_revisions(remote_extra,
3397
4249
                                        remote_branch.repository,
3398
4250
                                        verbose):
3401
4253
 
3402
4254
                if mine_only and not local_extra:
3403
4255
                    # We checked local, and found nothing extra
3404
 
                    self.outf.write('This branch is up to date.\n')
 
4256
                    message('This branch is up to date.\n')
3405
4257
                elif theirs_only and not remote_extra:
3406
4258
                    # We checked remote, and found nothing extra
3407
 
                    self.outf.write('Other branch is up to date.\n')
 
4259
                    message('Other branch is up to date.\n')
3408
4260
                elif not (mine_only or theirs_only or local_extra or
3409
4261
                          remote_extra):
3410
4262
                    # We checked both branches, and neither one had extra
3411
4263
                    # revisions
3412
 
                    self.outf.write("Branches are up to date.\n")
 
4264
                    message("Branches are up to date.\n")
3413
4265
            finally:
3414
4266
                remote_branch.unlock()
3415
4267
        finally:
3443
4295
 
3444
4296
class cmd_plugins(Command):
3445
4297
    """List the installed plugins.
3446
 
    
 
4298
 
3447
4299
    This command displays the list of installed plugins including
3448
4300
    version of plugin and a short description of each.
3449
4301
 
3526
4378
    This prints out the given file with an annotation on the left side
3527
4379
    indicating which revision, author and date introduced the change.
3528
4380
 
3529
 
    If the origin is the same for a run of consecutive lines, it is 
 
4381
    If the origin is the same for a run of consecutive lines, it is
3530
4382
    shown only at the top, unless the --all option is given.
3531
4383
    """
3532
4384
    # TODO: annotate directories; showing when each file was last changed
3533
 
    # TODO: if the working copy is modified, show annotations on that 
 
4385
    # TODO: if the working copy is modified, show annotations on that
3534
4386
    #       with new uncommitted lines marked
3535
4387
    aliases = ['ann', 'blame', 'praise']
3536
4388
    takes_args = ['filename']
3544
4396
    @display_command
3545
4397
    def run(self, filename, all=False, long=False, revision=None,
3546
4398
            show_ids=False):
3547
 
        from bzrlib.annotate import annotate_file
 
4399
        from bzrlib.annotate import annotate_file, annotate_file_tree
3548
4400
        wt, branch, relpath = \
3549
4401
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3550
4402
        if wt is not None:
3552
4404
        else:
3553
4405
            branch.lock_read()
3554
4406
        try:
3555
 
            if revision is None:
3556
 
                revision_id = branch.last_revision()
3557
 
            elif len(revision) != 1:
3558
 
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
3559
 
            else:
3560
 
                revision_id = revision[0].as_revision_id(branch)
3561
 
            tree = branch.repository.revision_tree(revision_id)
 
4407
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
3562
4408
            if wt is not None:
3563
4409
                file_id = wt.path2id(relpath)
3564
4410
            else:
3566
4412
            if file_id is None:
3567
4413
                raise errors.NotVersionedError(filename)
3568
4414
            file_version = tree.inventory[file_id].revision
3569
 
            annotate_file(branch, file_version, file_id, long, all, self.outf,
3570
 
                          show_ids=show_ids)
 
4415
            if wt is not None and revision is None:
 
4416
                # If there is a tree and we're not annotating historical
 
4417
                # versions, annotate the working tree's content.
 
4418
                annotate_file_tree(wt, file_id, self.outf, long, all,
 
4419
                    show_ids=show_ids)
 
4420
            else:
 
4421
                annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4422
                              show_ids=show_ids)
3571
4423
        finally:
3572
4424
            if wt is not None:
3573
4425
                wt.unlock()
3582
4434
    hidden = True # is this right ?
3583
4435
    takes_args = ['revision_id*']
3584
4436
    takes_options = ['revision']
3585
 
    
 
4437
 
3586
4438
    def run(self, revision_id_list=None, revision=None):
3587
4439
        if revision_id_list is not None and revision is not None:
3588
4440
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3648
4500
 
3649
4501
    Once converted into a checkout, commits must succeed on the master branch
3650
4502
    before they will be applied to the local branch.
 
4503
 
 
4504
    Bound branches use the nickname of its master branch unless it is set
 
4505
    locally, in which case binding will update the the local nickname to be
 
4506
    that of the master.
3651
4507
    """
3652
4508
 
3653
4509
    _see_also = ['checkouts', 'unbind']
3672
4528
        except errors.DivergedBranches:
3673
4529
            raise errors.BzrCommandError('These branches have diverged.'
3674
4530
                                         ' Try merging, and then bind again.')
 
4531
        if b.get_config().has_explicit_nickname():
 
4532
            b.nick = b_other.nick
3675
4533
 
3676
4534
 
3677
4535
class cmd_unbind(Command):
3812
4670
    holding the lock has been stopped.
3813
4671
 
3814
4672
    You can get information on what locks are open via the 'bzr info' command.
3815
 
    
 
4673
 
3816
4674
    :Examples:
3817
4675
        bzr break-lock
3818
4676
    """
3826
4684
            control.break_lock()
3827
4685
        except NotImplementedError:
3828
4686
            pass
3829
 
        
 
4687
 
3830
4688
 
3831
4689
class cmd_wait_until_signalled(Command):
3832
4690
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3850
4708
    takes_options = [
3851
4709
        Option('inet',
3852
4710
               help='Serve on stdin/out for use from inetd or sshd.'),
 
4711
        RegistryOption('protocol', 
 
4712
               help="Protocol to serve.", 
 
4713
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
 
4714
               value_switches=True),
3853
4715
        Option('port',
3854
4716
               help='Listen for connections on nominated port of the form '
3855
4717
                    '[hostname:]portnumber.  Passing 0 as the port number will '
3856
 
                    'result in a dynamically allocated port.  The default port is '
3857
 
                    '4155.',
 
4718
                    'result in a dynamically allocated port.  The default port '
 
4719
                    'depends on the protocol.',
3858
4720
               type=str),
3859
4721
        Option('directory',
3860
4722
               help='Serve contents of this directory.',
3866
4728
                ),
3867
4729
        ]
3868
4730
 
3869
 
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
3870
 
        from bzrlib import lockdir
3871
 
        from bzrlib.smart import medium, server
3872
 
        from bzrlib.transport import get_transport
3873
 
        from bzrlib.transport.chroot import ChrootServer
 
4731
    def get_host_and_port(self, port):
 
4732
        """Return the host and port to run the smart server on.
 
4733
 
 
4734
        If 'port' is None, None will be returned for the host and port.
 
4735
 
 
4736
        If 'port' has a colon in it, the string before the colon will be
 
4737
        interpreted as the host.
 
4738
 
 
4739
        :param port: A string of the port to run the server on.
 
4740
        :return: A tuple of (host, port), where 'host' is a host name or IP,
 
4741
            and port is an integer TCP/IP port.
 
4742
        """
 
4743
        host = None
 
4744
        if port is not None:
 
4745
            if ':' in port:
 
4746
                host, port = port.split(':')
 
4747
            port = int(port)
 
4748
        return host, port
 
4749
 
 
4750
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
 
4751
            protocol=None):
 
4752
        from bzrlib.transport import get_transport, transport_server_registry
3874
4753
        if directory is None:
3875
4754
            directory = os.getcwd()
 
4755
        if protocol is None:
 
4756
            protocol = transport_server_registry.get()
 
4757
        host, port = self.get_host_and_port(port)
3876
4758
        url = urlutils.local_path_to_url(directory)
3877
4759
        if not allow_writes:
3878
4760
            url = 'readonly+' + url
3879
 
        chroot_server = ChrootServer(get_transport(url))
3880
 
        chroot_server.setUp()
3881
 
        t = get_transport(chroot_server.get_url())
3882
 
        if inet:
3883
 
            smart_server = medium.SmartServerPipeStreamMedium(
3884
 
                sys.stdin, sys.stdout, t)
3885
 
        else:
3886
 
            host = medium.BZR_DEFAULT_INTERFACE
3887
 
            if port is None:
3888
 
                port = medium.BZR_DEFAULT_PORT
3889
 
            else:
3890
 
                if ':' in port:
3891
 
                    host, port = port.split(':')
3892
 
                port = int(port)
3893
 
            smart_server = server.SmartTCPServer(t, host=host, port=port)
3894
 
            print 'listening on port: ', smart_server.port
3895
 
            sys.stdout.flush()
3896
 
        # for the duration of this server, no UI output is permitted.
3897
 
        # note that this may cause problems with blackbox tests. This should
3898
 
        # be changed with care though, as we dont want to use bandwidth sending
3899
 
        # progress over stderr to smart server clients!
3900
 
        old_factory = ui.ui_factory
3901
 
        old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
3902
 
        try:
3903
 
            ui.ui_factory = ui.SilentUIFactory()
3904
 
            lockdir._DEFAULT_TIMEOUT_SECONDS = 0
3905
 
            smart_server.serve()
3906
 
        finally:
3907
 
            ui.ui_factory = old_factory
3908
 
            lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
 
4761
        transport = get_transport(url)
 
4762
        protocol(transport, host, port, inet)
3909
4763
 
3910
4764
 
3911
4765
class cmd_join(Command):
3912
 
    """Combine a subtree into its containing tree.
3913
 
    
3914
 
    This command is for experimental use only.  It requires the target tree
3915
 
    to be in dirstate-with-subtree format, which cannot be converted into
3916
 
    earlier formats.
 
4766
    """Combine a tree into its containing tree.
 
4767
 
 
4768
    This command requires the target tree to be in a rich-root format.
3917
4769
 
3918
4770
    The TREE argument should be an independent tree, inside another tree, but
3919
4771
    not part of it.  (Such trees can be produced by "bzr split", but also by
3922
4774
    The result is a combined tree, with the subtree no longer an independant
3923
4775
    part.  This is marked as a merge of the subtree into the containing tree,
3924
4776
    and all history is preserved.
3925
 
 
3926
 
    If --reference is specified, the subtree retains its independence.  It can
3927
 
    be branched by itself, and can be part of multiple projects at the same
3928
 
    time.  But operations performed in the containing tree, such as commit
3929
 
    and merge, will recurse into the subtree.
3930
4777
    """
3931
4778
 
3932
4779
    _see_also = ['split']
3933
4780
    takes_args = ['tree']
3934
4781
    takes_options = [
3935
 
            Option('reference', help='Join by reference.'),
 
4782
            Option('reference', help='Join by reference.', hidden=True),
3936
4783
            ]
3937
 
    hidden = True
3938
4784
 
3939
4785
    def run(self, tree, reference=False):
3940
4786
        sub_tree = WorkingTree.open(tree)
3958
4804
            try:
3959
4805
                containing_tree.subsume(sub_tree)
3960
4806
            except errors.BadSubsumeSource, e:
3961
 
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
 
4807
                raise errors.BzrCommandError("Cannot join %s.  %s" %
3962
4808
                                             (tree, e.reason))
3963
4809
 
3964
4810
 
3974
4820
    branch.  Commits in the top-level tree will not apply to the new subtree.
3975
4821
    """
3976
4822
 
3977
 
    # join is not un-hidden yet
3978
 
    #_see_also = ['join']
 
4823
    _see_also = ['join']
3979
4824
    takes_args = ['tree']
3980
4825
 
3981
4826
    def run(self, tree):
3986
4831
        try:
3987
4832
            containing_tree.extract(sub_id)
3988
4833
        except errors.RootNotRich:
3989
 
            raise errors.UpgradeRequired(containing_tree.branch.base)
 
4834
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
3990
4835
 
3991
4836
 
3992
4837
class cmd_merge_directive(Command):
4089
4934
 
4090
4935
 
4091
4936
class cmd_send(Command):
4092
 
    """Mail or create a merge-directive for submiting changes.
 
4937
    """Mail or create a merge-directive for submitting changes.
4093
4938
 
4094
4939
    A merge directive provides many things needed for requesting merges:
4095
4940
 
4117
4962
    Mail is sent using your preferred mail program.  This should be transparent
4118
4963
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
4119
4964
    If the preferred client can't be found (or used), your editor will be used.
4120
 
    
 
4965
 
4121
4966
    To use a specific mail program, set the mail_client configuration option.
4122
4967
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
4123
 
    specific clients are "evolution", "kmail", "mutt", and "thunderbird";
4124
 
    generic options are "default", "editor", "emacsclient", "mapi", and
4125
 
    "xdg-email".  Plugins may also add supported clients.
 
4968
    specific clients are "claws", "evolution", "kmail", "mutt", and
 
4969
    "thunderbird"; generic options are "default", "editor", "emacsclient",
 
4970
    "mapi", and "xdg-email".  Plugins may also add supported clients.
4126
4971
 
4127
4972
    If mail is being sent, a to address is required.  This can be supplied
4128
4973
    either on the commandline, by setting the submit_to configuration
4129
 
    option in the branch itself or the child_submit_to configuration option 
 
4974
    option in the branch itself or the child_submit_to configuration option
4130
4975
    in the submit branch.
4131
4976
 
4132
4977
    Two formats are currently supported: "4" uses revision bundle format 4 and
4134
4979
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
4135
4980
    default.  "0.9" uses revision bundle format 0.9 and merge directive
4136
4981
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
4137
 
    
4138
 
    Merge directives are applied using the merge command or the pull command.
 
4982
 
 
4983
    The merge directives created by bzr send may be applied using bzr merge or
 
4984
    bzr pull by specifying a file containing a merge directive as the location.
4139
4985
    """
4140
4986
 
4141
4987
    encoding_type = 'exact'
4160
5006
               help='Write merge directive to this file; '
4161
5007
                    'use - for stdout.',
4162
5008
               type=unicode),
 
5009
        Option('strict',
 
5010
               help='Refuse to send if there are uncommitted changes in'
 
5011
               ' the working tree, --no-strict disables the check.'),
4163
5012
        Option('mail-to', help='Mail the request to this address.',
4164
5013
               type=unicode),
4165
5014
        'revision',
4166
5015
        'message',
4167
 
        RegistryOption.from_kwargs('format',
4168
 
        'Use the specified output format.',
4169
 
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
4170
 
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
5016
        Option('body', help='Body for the email.', type=unicode),
 
5017
        RegistryOption('format',
 
5018
                       help='Use the specified output format.',
 
5019
                       lazy_registry=('bzrlib.send', 'format_registry')),
4171
5020
        ]
4172
5021
 
4173
5022
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4174
5023
            no_patch=False, revision=None, remember=False, output=None,
4175
 
            format='4', mail_to=None, message=None, **kwargs):
4176
 
        return self._run(submit_branch, revision, public_branch, remember,
4177
 
                         format, no_bundle, no_patch, output,
4178
 
                         kwargs.get('from', '.'), mail_to, message)
4179
 
 
4180
 
    def _run(self, submit_branch, revision, public_branch, remember, format,
4181
 
             no_bundle, no_patch, output, from_, mail_to, message):
4182
 
        from bzrlib.revision import NULL_REVISION
4183
 
        branch = Branch.open_containing(from_)[0]
4184
 
        if output is None:
4185
 
            outfile = StringIO()
4186
 
        elif output == '-':
4187
 
            outfile = self.outf
4188
 
        else:
4189
 
            outfile = open(output, 'wb')
4190
 
        # we may need to write data into branch's repository to calculate
4191
 
        # the data to send.
4192
 
        branch.lock_write()
4193
 
        try:
4194
 
            if output is None:
4195
 
                config = branch.get_config()
4196
 
                if mail_to is None:
4197
 
                    mail_to = config.get_user_option('submit_to')
4198
 
                mail_client = config.get_mail_client()
4199
 
            if remember and submit_branch is None:
4200
 
                raise errors.BzrCommandError(
4201
 
                    '--remember requires a branch to be specified.')
4202
 
            stored_submit_branch = branch.get_submit_branch()
4203
 
            remembered_submit_branch = None
4204
 
            if submit_branch is None:
4205
 
                submit_branch = stored_submit_branch
4206
 
                remembered_submit_branch = "submit"
4207
 
            else:
4208
 
                if stored_submit_branch is None or remember:
4209
 
                    branch.set_submit_branch(submit_branch)
4210
 
            if submit_branch is None:
4211
 
                submit_branch = branch.get_parent()
4212
 
                remembered_submit_branch = "parent"
4213
 
            if submit_branch is None:
4214
 
                raise errors.BzrCommandError('No submit branch known or'
4215
 
                                             ' specified')
4216
 
            if remembered_submit_branch is not None:
4217
 
                note('Using saved %s location "%s" to determine what '
4218
 
                        'changes to submit.', remembered_submit_branch,
4219
 
                        submit_branch)
4220
 
 
4221
 
            if mail_to is None:
4222
 
                submit_config = Branch.open(submit_branch).get_config()
4223
 
                mail_to = submit_config.get_user_option("child_submit_to")
4224
 
 
4225
 
            stored_public_branch = branch.get_public_branch()
4226
 
            if public_branch is None:
4227
 
                public_branch = stored_public_branch
4228
 
            elif stored_public_branch is None or remember:
4229
 
                branch.set_public_branch(public_branch)
4230
 
            if no_bundle and public_branch is None:
4231
 
                raise errors.BzrCommandError('No public branch specified or'
4232
 
                                             ' known')
4233
 
            base_revision_id = None
4234
 
            revision_id = None
4235
 
            if revision is not None:
4236
 
                if len(revision) > 2:
4237
 
                    raise errors.BzrCommandError('bzr send takes '
4238
 
                        'at most two one revision identifiers')
4239
 
                revision_id = revision[-1].as_revision_id(branch)
4240
 
                if len(revision) == 2:
4241
 
                    base_revision_id = revision[0].as_revision_id(branch)
4242
 
            if revision_id is None:
4243
 
                revision_id = branch.last_revision()
4244
 
            if revision_id == NULL_REVISION:
4245
 
                raise errors.BzrCommandError('No revisions to submit.')
4246
 
            if format == '4':
4247
 
                directive = merge_directive.MergeDirective2.from_objects(
4248
 
                    branch.repository, revision_id, time.time(),
4249
 
                    osutils.local_time_offset(), submit_branch,
4250
 
                    public_branch=public_branch, include_patch=not no_patch,
4251
 
                    include_bundle=not no_bundle, message=message,
4252
 
                    base_revision_id=base_revision_id)
4253
 
            elif format == '0.9':
4254
 
                if not no_bundle:
4255
 
                    if not no_patch:
4256
 
                        patch_type = 'bundle'
4257
 
                    else:
4258
 
                        raise errors.BzrCommandError('Format 0.9 does not'
4259
 
                            ' permit bundle with no patch')
4260
 
                else:
4261
 
                    if not no_patch:
4262
 
                        patch_type = 'diff'
4263
 
                    else:
4264
 
                        patch_type = None
4265
 
                directive = merge_directive.MergeDirective.from_objects(
4266
 
                    branch.repository, revision_id, time.time(),
4267
 
                    osutils.local_time_offset(), submit_branch,
4268
 
                    public_branch=public_branch, patch_type=patch_type,
4269
 
                    message=message)
4270
 
 
4271
 
            outfile.writelines(directive.to_lines())
4272
 
            if output is None:
4273
 
                subject = '[MERGE] '
4274
 
                if message is not None:
4275
 
                    subject += message
4276
 
                else:
4277
 
                    revision = branch.repository.get_revision(revision_id)
4278
 
                    subject += revision.get_summary()
4279
 
                basename = directive.get_disk_name(branch)
4280
 
                mail_client.compose_merge_request(mail_to, subject,
4281
 
                                                  outfile.getvalue(), basename)
4282
 
        finally:
4283
 
            if output != '-':
4284
 
                outfile.close()
4285
 
            branch.unlock()
 
5024
            format=None, mail_to=None, message=None, body=None,
 
5025
            strict=None, **kwargs):
 
5026
        from bzrlib.send import send
 
5027
        return send(submit_branch, revision, public_branch, remember,
 
5028
                    format, no_bundle, no_patch, output,
 
5029
                    kwargs.get('from', '.'), mail_to, message, body,
 
5030
                    self.outf,
 
5031
                    strict=strict)
4286
5032
 
4287
5033
 
4288
5034
class cmd_bundle_revisions(cmd_send):
4289
 
 
4290
 
    """Create a merge-directive for submiting changes.
 
5035
    """Create a merge-directive for submitting changes.
4291
5036
 
4292
5037
    A merge directive provides many things needed for requesting merges:
4293
5038
 
4333
5078
               type=unicode),
4334
5079
        Option('output', short_name='o', help='Write directive to this file.',
4335
5080
               type=unicode),
 
5081
        Option('strict',
 
5082
               help='Refuse to bundle revisions if there are uncommitted'
 
5083
               ' changes in the working tree, --no-strict disables the check.'),
4336
5084
        'revision',
4337
 
        RegistryOption.from_kwargs('format',
4338
 
        'Use the specified output format.',
4339
 
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
4340
 
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
5085
        RegistryOption('format',
 
5086
                       help='Use the specified output format.',
 
5087
                       lazy_registry=('bzrlib.send', 'format_registry')),
4341
5088
        ]
4342
5089
    aliases = ['bundle']
4343
5090
 
4347
5094
 
4348
5095
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4349
5096
            no_patch=False, revision=None, remember=False, output=None,
4350
 
            format='4', **kwargs):
 
5097
            format=None, strict=None, **kwargs):
4351
5098
        if output is None:
4352
5099
            output = '-'
4353
 
        return self._run(submit_branch, revision, public_branch, remember,
 
5100
        from bzrlib.send import send
 
5101
        return send(submit_branch, revision, public_branch, remember,
4354
5102
                         format, no_bundle, no_patch, output,
4355
 
                         kwargs.get('from', '.'), None, None)
 
5103
                         kwargs.get('from', '.'), None, None, None,
 
5104
                         self.outf, strict=strict)
4356
5105
 
4357
5106
 
4358
5107
class cmd_tag(Command):
4359
5108
    """Create, remove or modify a tag naming a revision.
4360
 
    
 
5109
 
4361
5110
    Tags give human-meaningful names to revisions.  Commands that take a -r
4362
5111
    (--revision) option can be given -rtag:X, where X is any previously
4363
5112
    created tag.
4365
5114
    Tags are stored in the branch.  Tags are copied from one branch to another
4366
5115
    along when you branch, push, pull or merge.
4367
5116
 
4368
 
    It is an error to give a tag name that already exists unless you pass 
 
5117
    It is an error to give a tag name that already exists unless you pass
4369
5118
    --force, in which case the tag is moved to point to the new revision.
4370
5119
 
4371
5120
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
4437
5186
            time='Sort tags chronologically.',
4438
5187
            ),
4439
5188
        'show-ids',
 
5189
        'revision',
4440
5190
    ]
4441
5191
 
4442
5192
    @display_command
4444
5194
            directory='.',
4445
5195
            sort='alpha',
4446
5196
            show_ids=False,
 
5197
            revision=None,
4447
5198
            ):
4448
5199
        branch, relpath = Branch.open_containing(directory)
 
5200
 
4449
5201
        tags = branch.tags.get_tag_dict().items()
4450
5202
        if not tags:
4451
5203
            return
4452
 
        if sort == 'alpha':
4453
 
            tags.sort()
4454
 
        elif sort == 'time':
4455
 
            timestamps = {}
4456
 
            for tag, revid in tags:
4457
 
                try:
4458
 
                    revobj = branch.repository.get_revision(revid)
4459
 
                except errors.NoSuchRevision:
4460
 
                    timestamp = sys.maxint # place them at the end
4461
 
                else:
4462
 
                    timestamp = revobj.timestamp
4463
 
                timestamps[revid] = timestamp
4464
 
            tags.sort(key=lambda x: timestamps[x[1]])
4465
 
        if not show_ids:
4466
 
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4467
 
            revno_map = branch.get_revision_id_to_revno_map()
4468
 
            tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4469
 
                        for tag, revid in tags ]
 
5204
 
 
5205
        branch.lock_read()
 
5206
        try:
 
5207
            if revision:
 
5208
                graph = branch.repository.get_graph()
 
5209
                rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5210
                revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5211
                # only show revisions between revid1 and revid2 (inclusive)
 
5212
                tags = [(tag, revid) for tag, revid in tags if
 
5213
                    graph.is_between(revid, revid1, revid2)]
 
5214
            if sort == 'alpha':
 
5215
                tags.sort()
 
5216
            elif sort == 'time':
 
5217
                timestamps = {}
 
5218
                for tag, revid in tags:
 
5219
                    try:
 
5220
                        revobj = branch.repository.get_revision(revid)
 
5221
                    except errors.NoSuchRevision:
 
5222
                        timestamp = sys.maxint # place them at the end
 
5223
                    else:
 
5224
                        timestamp = revobj.timestamp
 
5225
                    timestamps[revid] = timestamp
 
5226
                tags.sort(key=lambda x: timestamps[x[1]])
 
5227
            if not show_ids:
 
5228
                # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
5229
                for index, (tag, revid) in enumerate(tags):
 
5230
                    try:
 
5231
                        revno = branch.revision_id_to_dotted_revno(revid)
 
5232
                        if isinstance(revno, tuple):
 
5233
                            revno = '.'.join(map(str, revno))
 
5234
                    except errors.NoSuchRevision:
 
5235
                        # Bad tag data/merges can lead to tagged revisions
 
5236
                        # which are not in this branch. Fail gracefully ...
 
5237
                        revno = '?'
 
5238
                    tags[index] = (tag, revno)
 
5239
        finally:
 
5240
            branch.unlock()
4470
5241
        for tag, revspec in tags:
4471
5242
            self.outf.write('%-20s %s\n' % (tag, revspec))
4472
5243
 
4487
5258
 
4488
5259
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4489
5260
    takes_args = ['location?']
4490
 
    takes_options = [RegistryOption.from_kwargs('target_type',
4491
 
                     title='Target type',
4492
 
                     help='The type to reconfigure the directory to.',
4493
 
                     value_switches=True, enum_switch=False,
4494
 
                     branch='Reconfigure to be an unbound branch '
4495
 
                        'with no working tree.',
4496
 
                     tree='Reconfigure to be an unbound branch '
4497
 
                        'with a working tree.',
4498
 
                     checkout='Reconfigure to be a bound branch '
4499
 
                        'with a working tree.',
4500
 
                     lightweight_checkout='Reconfigure to be a lightweight'
4501
 
                     ' checkout (with no local history).',
4502
 
                     standalone='Reconfigure to be a standalone branch '
4503
 
                        '(i.e. stop using shared repository).',
4504
 
                     use_shared='Reconfigure to use a shared repository.'),
4505
 
                     Option('bind-to', help='Branch to bind checkout to.',
4506
 
                            type=str),
4507
 
                     Option('force',
4508
 
                        help='Perform reconfiguration even if local changes'
4509
 
                        ' will be lost.')
4510
 
                     ]
 
5261
    takes_options = [
 
5262
        RegistryOption.from_kwargs(
 
5263
            'target_type',
 
5264
            title='Target type',
 
5265
            help='The type to reconfigure the directory to.',
 
5266
            value_switches=True, enum_switch=False,
 
5267
            branch='Reconfigure to be an unbound branch with no working tree.',
 
5268
            tree='Reconfigure to be an unbound branch with a working tree.',
 
5269
            checkout='Reconfigure to be a bound branch with a working tree.',
 
5270
            lightweight_checkout='Reconfigure to be a lightweight'
 
5271
                ' checkout (with no local history).',
 
5272
            standalone='Reconfigure to be a standalone branch '
 
5273
                '(i.e. stop using shared repository).',
 
5274
            use_shared='Reconfigure to use a shared repository.',
 
5275
            with_trees='Reconfigure repository to create '
 
5276
                'working trees on branches by default.',
 
5277
            with_no_trees='Reconfigure repository to not create '
 
5278
                'working trees on branches by default.'
 
5279
            ),
 
5280
        Option('bind-to', help='Branch to bind checkout to.', type=str),
 
5281
        Option('force',
 
5282
            help='Perform reconfiguration even if local changes'
 
5283
            ' will be lost.'),
 
5284
        Option('stacked-on',
 
5285
            help='Reconfigure a branch to be stacked on another branch.',
 
5286
            type=unicode,
 
5287
            ),
 
5288
        Option('unstacked',
 
5289
            help='Reconfigure a branch to be unstacked.  This '
 
5290
                'may require copying substantial data into it.',
 
5291
            ),
 
5292
        ]
4511
5293
 
4512
 
    def run(self, location=None, target_type=None, bind_to=None, force=False):
 
5294
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5295
            stacked_on=None,
 
5296
            unstacked=None):
4513
5297
        directory = bzrdir.BzrDir.open(location)
 
5298
        if stacked_on and unstacked:
 
5299
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5300
        elif stacked_on is not None:
 
5301
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
 
5302
        elif unstacked:
 
5303
            reconfigure.ReconfigureUnstacked().apply(directory)
 
5304
        # At the moment you can use --stacked-on and a different
 
5305
        # reconfiguration shape at the same time; there seems no good reason
 
5306
        # to ban it.
4514
5307
        if target_type is None:
4515
 
            raise errors.BzrCommandError('No target configuration specified')
 
5308
            if stacked_on or unstacked:
 
5309
                return
 
5310
            else:
 
5311
                raise errors.BzrCommandError('No target configuration '
 
5312
                    'specified')
4516
5313
        elif target_type == 'branch':
4517
5314
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4518
5315
        elif target_type == 'tree':
4519
5316
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4520
5317
        elif target_type == 'checkout':
4521
 
            reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4522
 
                                                                  bind_to)
 
5318
            reconfiguration = reconfigure.Reconfigure.to_checkout(
 
5319
                directory, bind_to)
4523
5320
        elif target_type == 'lightweight-checkout':
4524
5321
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4525
5322
                directory, bind_to)
4527
5324
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4528
5325
        elif target_type == 'standalone':
4529
5326
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
 
5327
        elif target_type == 'with-trees':
 
5328
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5329
                directory, True)
 
5330
        elif target_type == 'with-no-trees':
 
5331
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5332
                directory, False)
4530
5333
        reconfiguration.apply(force)
4531
5334
 
4532
5335
 
4533
5336
class cmd_switch(Command):
4534
5337
    """Set the branch of a checkout and update.
4535
 
    
 
5338
 
4536
5339
    For lightweight checkouts, this changes the branch being referenced.
4537
5340
    For heavyweight checkouts, this checks that there are no local commits
4538
5341
    versus the current bound branch, then it makes the local branch a mirror
4539
5342
    of the new location and binds to it.
4540
 
    
 
5343
 
4541
5344
    In both cases, the working tree is updated and uncommitted changes
4542
5345
    are merged. The user can commit or revert these as they desire.
4543
5346
 
4547
5350
    directory of the current branch. For example, if you are currently in a
4548
5351
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4549
5352
    /path/to/newbranch.
 
5353
 
 
5354
    Bound branches use the nickname of its master branch unless it is set
 
5355
    locally, in which case switching will update the the local nickname to be
 
5356
    that of the master.
4550
5357
    """
4551
5358
 
4552
5359
    takes_args = ['to_location']
4553
5360
    takes_options = [Option('force',
4554
 
                        help='Switch even if local commits will be lost.')
 
5361
                        help='Switch even if local commits will be lost.'),
 
5362
                     Option('create-branch', short_name='b',
 
5363
                        help='Create the target branch from this one before'
 
5364
                             ' switching to it.'),
4555
5365
                     ]
4556
5366
 
4557
 
    def run(self, to_location, force=False):
 
5367
    def run(self, to_location, force=False, create_branch=False):
4558
5368
        from bzrlib import switch
4559
5369
        tree_location = '.'
4560
5370
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4561
5371
        try:
4562
 
            to_branch = Branch.open(to_location)
 
5372
            branch = control_dir.open_branch()
 
5373
            had_explicit_nick = branch.get_config().has_explicit_nickname()
4563
5374
        except errors.NotBranchError:
4564
 
            to_branch = Branch.open(
4565
 
                control_dir.open_branch().base + '../' + to_location)
 
5375
            branch = None
 
5376
            had_explicit_nick = False
 
5377
        if create_branch:
 
5378
            if branch is None:
 
5379
                raise errors.BzrCommandError('cannot create branch without'
 
5380
                                             ' source branch')
 
5381
            if '/' not in to_location and '\\' not in to_location:
 
5382
                # This path is meant to be relative to the existing branch
 
5383
                this_url = self._get_branch_location(control_dir)
 
5384
                to_location = urlutils.join(this_url, '..', to_location)
 
5385
            to_branch = branch.bzrdir.sprout(to_location,
 
5386
                                 possible_transports=[branch.bzrdir.root_transport],
 
5387
                                 source_branch=branch).open_branch()
 
5388
            # try:
 
5389
            #     from_branch = control_dir.open_branch()
 
5390
            # except errors.NotBranchError:
 
5391
            #     raise BzrCommandError('Cannot create a branch from this'
 
5392
            #         ' location when we cannot open this branch')
 
5393
            # from_branch.bzrdir.sprout(
 
5394
            pass
 
5395
        else:
 
5396
            try:
 
5397
                to_branch = Branch.open(to_location)
 
5398
            except errors.NotBranchError:
 
5399
                this_url = self._get_branch_location(control_dir)
 
5400
                to_branch = Branch.open(
 
5401
                    urlutils.join(this_url, '..', to_location))
4566
5402
        switch.switch(control_dir, to_branch, force)
 
5403
        if had_explicit_nick:
 
5404
            branch = control_dir.open_branch() #get the new branch!
 
5405
            branch.nick = to_branch.nick
4567
5406
        note('Switched to branch: %s',
4568
5407
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4569
5408
 
 
5409
    def _get_branch_location(self, control_dir):
 
5410
        """Return location of branch for this control dir."""
 
5411
        try:
 
5412
            this_branch = control_dir.open_branch()
 
5413
            # This may be a heavy checkout, where we want the master branch
 
5414
            master_location = this_branch.get_bound_location()
 
5415
            if master_location is not None:
 
5416
                return master_location
 
5417
            # If not, use a local sibling
 
5418
            return this_branch.base
 
5419
        except errors.NotBranchError:
 
5420
            format = control_dir.find_branch_format()
 
5421
            if getattr(format, 'get_reference', None) is not None:
 
5422
                return format.get_reference(control_dir)
 
5423
            else:
 
5424
                return control_dir.root_transport.base
 
5425
 
 
5426
 
 
5427
class cmd_view(Command):
 
5428
    """Manage filtered views.
 
5429
 
 
5430
    Views provide a mask over the tree so that users can focus on
 
5431
    a subset of a tree when doing their work. After creating a view,
 
5432
    commands that support a list of files - status, diff, commit, etc -
 
5433
    effectively have that list of files implicitly given each time.
 
5434
    An explicit list of files can still be given but those files
 
5435
    must be within the current view.
 
5436
 
 
5437
    In most cases, a view has a short life-span: it is created to make
 
5438
    a selected change and is deleted once that change is committed.
 
5439
    At other times, you may wish to create one or more named views
 
5440
    and switch between them.
 
5441
 
 
5442
    To disable the current view without deleting it, you can switch to
 
5443
    the pseudo view called ``off``. This can be useful when you need
 
5444
    to see the whole tree for an operation or two (e.g. merge) but
 
5445
    want to switch back to your view after that.
 
5446
 
 
5447
    :Examples:
 
5448
      To define the current view::
 
5449
 
 
5450
        bzr view file1 dir1 ...
 
5451
 
 
5452
      To list the current view::
 
5453
 
 
5454
        bzr view
 
5455
 
 
5456
      To delete the current view::
 
5457
 
 
5458
        bzr view --delete
 
5459
 
 
5460
      To disable the current view without deleting it::
 
5461
 
 
5462
        bzr view --switch off
 
5463
 
 
5464
      To define a named view and switch to it::
 
5465
 
 
5466
        bzr view --name view-name file1 dir1 ...
 
5467
 
 
5468
      To list a named view::
 
5469
 
 
5470
        bzr view --name view-name
 
5471
 
 
5472
      To delete a named view::
 
5473
 
 
5474
        bzr view --name view-name --delete
 
5475
 
 
5476
      To switch to a named view::
 
5477
 
 
5478
        bzr view --switch view-name
 
5479
 
 
5480
      To list all views defined::
 
5481
 
 
5482
        bzr view --all
 
5483
 
 
5484
      To delete all views::
 
5485
 
 
5486
        bzr view --delete --all
 
5487
    """
 
5488
 
 
5489
    _see_also = []
 
5490
    takes_args = ['file*']
 
5491
    takes_options = [
 
5492
        Option('all',
 
5493
            help='Apply list or delete action to all views.',
 
5494
            ),
 
5495
        Option('delete',
 
5496
            help='Delete the view.',
 
5497
            ),
 
5498
        Option('name',
 
5499
            help='Name of the view to define, list or delete.',
 
5500
            type=unicode,
 
5501
            ),
 
5502
        Option('switch',
 
5503
            help='Name of the view to switch to.',
 
5504
            type=unicode,
 
5505
            ),
 
5506
        ]
 
5507
 
 
5508
    def run(self, file_list,
 
5509
            all=False,
 
5510
            delete=False,
 
5511
            name=None,
 
5512
            switch=None,
 
5513
            ):
 
5514
        tree, file_list = tree_files(file_list, apply_view=False)
 
5515
        current_view, view_dict = tree.views.get_view_info()
 
5516
        if name is None:
 
5517
            name = current_view
 
5518
        if delete:
 
5519
            if file_list:
 
5520
                raise errors.BzrCommandError(
 
5521
                    "Both --delete and a file list specified")
 
5522
            elif switch:
 
5523
                raise errors.BzrCommandError(
 
5524
                    "Both --delete and --switch specified")
 
5525
            elif all:
 
5526
                tree.views.set_view_info(None, {})
 
5527
                self.outf.write("Deleted all views.\n")
 
5528
            elif name is None:
 
5529
                raise errors.BzrCommandError("No current view to delete")
 
5530
            else:
 
5531
                tree.views.delete_view(name)
 
5532
                self.outf.write("Deleted '%s' view.\n" % name)
 
5533
        elif switch:
 
5534
            if file_list:
 
5535
                raise errors.BzrCommandError(
 
5536
                    "Both --switch and a file list specified")
 
5537
            elif all:
 
5538
                raise errors.BzrCommandError(
 
5539
                    "Both --switch and --all specified")
 
5540
            elif switch == 'off':
 
5541
                if current_view is None:
 
5542
                    raise errors.BzrCommandError("No current view to disable")
 
5543
                tree.views.set_view_info(None, view_dict)
 
5544
                self.outf.write("Disabled '%s' view.\n" % (current_view))
 
5545
            else:
 
5546
                tree.views.set_view_info(switch, view_dict)
 
5547
                view_str = views.view_display_str(tree.views.lookup_view())
 
5548
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
 
5549
        elif all:
 
5550
            if view_dict:
 
5551
                self.outf.write('Views defined:\n')
 
5552
                for view in sorted(view_dict):
 
5553
                    if view == current_view:
 
5554
                        active = "=>"
 
5555
                    else:
 
5556
                        active = "  "
 
5557
                    view_str = views.view_display_str(view_dict[view])
 
5558
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
 
5559
            else:
 
5560
                self.outf.write('No views defined.\n')
 
5561
        elif file_list:
 
5562
            if name is None:
 
5563
                # No name given and no current view set
 
5564
                name = 'my'
 
5565
            elif name == 'off':
 
5566
                raise errors.BzrCommandError(
 
5567
                    "Cannot change the 'off' pseudo view")
 
5568
            tree.views.set_view(name, sorted(file_list))
 
5569
            view_str = views.view_display_str(tree.views.lookup_view())
 
5570
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
 
5571
        else:
 
5572
            # list the files
 
5573
            if name is None:
 
5574
                # No name given and no current view set
 
5575
                self.outf.write('No current view.\n')
 
5576
            else:
 
5577
                view_str = views.view_display_str(tree.views.lookup_view(name))
 
5578
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
 
5579
 
4570
5580
 
4571
5581
class cmd_hooks(Command):
4572
 
    """Show a branch's currently registered hooks.
4573
 
    """
4574
 
 
4575
 
    hidden = True
4576
 
    takes_args = ['path?']
4577
 
 
4578
 
    def run(self, path=None):
 
5582
    """Show hooks."""
 
5583
 
 
5584
    hidden = True
 
5585
 
 
5586
    def run(self):
 
5587
        for hook_key in sorted(hooks.known_hooks.keys()):
 
5588
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
 
5589
            self.outf.write("%s:\n" % type(some_hooks).__name__)
 
5590
            for hook_name, hook_point in sorted(some_hooks.items()):
 
5591
                self.outf.write("  %s:\n" % (hook_name,))
 
5592
                found_hooks = list(hook_point)
 
5593
                if found_hooks:
 
5594
                    for hook in found_hooks:
 
5595
                        self.outf.write("    %s\n" %
 
5596
                                        (some_hooks.get_hook_name(hook),))
 
5597
                else:
 
5598
                    self.outf.write("    <no hooks installed>\n")
 
5599
 
 
5600
 
 
5601
class cmd_shelve(Command):
 
5602
    """Temporarily set aside some changes from the current tree.
 
5603
 
 
5604
    Shelve allows you to temporarily put changes you've made "on the shelf",
 
5605
    ie. out of the way, until a later time when you can bring them back from
 
5606
    the shelf with the 'unshelve' command.  The changes are stored alongside
 
5607
    your working tree, and so they aren't propagated along with your branch nor
 
5608
    will they survive its deletion.
 
5609
 
 
5610
    If shelve --list is specified, previously-shelved changes are listed.
 
5611
 
 
5612
    Shelve is intended to help separate several sets of changes that have
 
5613
    been inappropriately mingled.  If you just want to get rid of all changes
 
5614
    and you don't need to restore them later, use revert.  If you want to
 
5615
    shelve all text changes at once, use shelve --all.
 
5616
 
 
5617
    If filenames are specified, only the changes to those files will be
 
5618
    shelved. Other files will be left untouched.
 
5619
 
 
5620
    If a revision is specified, changes since that revision will be shelved.
 
5621
 
 
5622
    You can put multiple items on the shelf, and by default, 'unshelve' will
 
5623
    restore the most recently shelved changes.
 
5624
    """
 
5625
 
 
5626
    takes_args = ['file*']
 
5627
 
 
5628
    takes_options = [
 
5629
        'revision',
 
5630
        Option('all', help='Shelve all changes.'),
 
5631
        'message',
 
5632
        RegistryOption('writer', 'Method to use for writing diffs.',
 
5633
                       bzrlib.option.diff_writer_registry,
 
5634
                       value_switches=True, enum_switch=False),
 
5635
 
 
5636
        Option('list', help='List shelved changes.'),
 
5637
        Option('destroy',
 
5638
               help='Destroy removed changes instead of shelving them.'),
 
5639
    ]
 
5640
    _see_also = ['unshelve']
 
5641
 
 
5642
    def run(self, revision=None, all=False, file_list=None, message=None,
 
5643
            writer=None, list=False, destroy=False):
 
5644
        if list:
 
5645
            return self.run_for_list()
 
5646
        from bzrlib.shelf_ui import Shelver
 
5647
        if writer is None:
 
5648
            writer = bzrlib.option.diff_writer_registry.get()
 
5649
        try:
 
5650
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
 
5651
                file_list, message, destroy=destroy)
 
5652
            try:
 
5653
                shelver.run()
 
5654
            finally:
 
5655
                shelver.work_tree.unlock()
 
5656
        except errors.UserAbort:
 
5657
            return 0
 
5658
 
 
5659
    def run_for_list(self):
 
5660
        tree = WorkingTree.open_containing('.')[0]
 
5661
        tree.lock_read()
 
5662
        try:
 
5663
            manager = tree.get_shelf_manager()
 
5664
            shelves = manager.active_shelves()
 
5665
            if len(shelves) == 0:
 
5666
                note('No shelved changes.')
 
5667
                return 0
 
5668
            for shelf_id in reversed(shelves):
 
5669
                message = manager.get_metadata(shelf_id).get('message')
 
5670
                if message is None:
 
5671
                    message = '<no message>'
 
5672
                self.outf.write('%3d: %s\n' % (shelf_id, message))
 
5673
            return 1
 
5674
        finally:
 
5675
            tree.unlock()
 
5676
 
 
5677
 
 
5678
class cmd_unshelve(Command):
 
5679
    """Restore shelved changes.
 
5680
 
 
5681
    By default, the most recently shelved changes are restored. However if you
 
5682
    specify a shelf by id those changes will be restored instead.  This works
 
5683
    best when the changes don't depend on each other.
 
5684
    """
 
5685
 
 
5686
    takes_args = ['shelf_id?']
 
5687
    takes_options = [
 
5688
        RegistryOption.from_kwargs(
 
5689
            'action', help="The action to perform.",
 
5690
            enum_switch=False, value_switches=True,
 
5691
            apply="Apply changes and remove from the shelf.",
 
5692
            dry_run="Show changes, but do not apply or remove them.",
 
5693
            delete_only="Delete changes without applying them."
 
5694
        )
 
5695
    ]
 
5696
    _see_also = ['shelve']
 
5697
 
 
5698
    def run(self, shelf_id=None, action='apply'):
 
5699
        from bzrlib.shelf_ui import Unshelver
 
5700
        unshelver = Unshelver.from_args(shelf_id, action)
 
5701
        try:
 
5702
            unshelver.run()
 
5703
        finally:
 
5704
            unshelver.tree.unlock()
 
5705
 
 
5706
 
 
5707
class cmd_clean_tree(Command):
 
5708
    """Remove unwanted files from working tree.
 
5709
 
 
5710
    By default, only unknown files, not ignored files, are deleted.  Versioned
 
5711
    files are never deleted.
 
5712
 
 
5713
    Another class is 'detritus', which includes files emitted by bzr during
 
5714
    normal operations and selftests.  (The value of these files decreases with
 
5715
    time.)
 
5716
 
 
5717
    If no options are specified, unknown files are deleted.  Otherwise, option
 
5718
    flags are respected, and may be combined.
 
5719
 
 
5720
    To check what clean-tree will do, use --dry-run.
 
5721
    """
 
5722
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5723
                     Option('detritus', help='Delete conflict files, merge'
 
5724
                            ' backups, and failed selftest dirs.'),
 
5725
                     Option('unknown',
 
5726
                            help='Delete files unknown to bzr (default).'),
 
5727
                     Option('dry-run', help='Show files to delete instead of'
 
5728
                            ' deleting them.'),
 
5729
                     Option('force', help='Do not prompt before deleting.')]
 
5730
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
 
5731
            force=False):
 
5732
        from bzrlib.clean_tree import clean_tree
 
5733
        if not (unknown or ignored or detritus):
 
5734
            unknown = True
 
5735
        if dry_run:
 
5736
            force = True
 
5737
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5738
                   dry_run=dry_run, no_prompt=force)
 
5739
 
 
5740
 
 
5741
class cmd_reference(Command):
 
5742
    """list, view and set branch locations for nested trees.
 
5743
 
 
5744
    If no arguments are provided, lists the branch locations for nested trees.
 
5745
    If one argument is provided, display the branch location for that tree.
 
5746
    If two arguments are provided, set the branch location for that tree.
 
5747
    """
 
5748
 
 
5749
    hidden = True
 
5750
 
 
5751
    takes_args = ['path?', 'location?']
 
5752
 
 
5753
    def run(self, path=None, location=None):
 
5754
        branchdir = '.'
 
5755
        if path is not None:
 
5756
            branchdir = path
 
5757
        tree, branch, relpath =(
 
5758
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
 
5759
        if path is not None:
 
5760
            path = relpath
 
5761
        if tree is None:
 
5762
            tree = branch.basis_tree()
4579
5763
        if path is None:
4580
 
            path = '.'
4581
 
        branch_hooks = Branch.open(path).hooks
4582
 
        for hook_type in branch_hooks:
4583
 
            hooks = branch_hooks[hook_type]
4584
 
            self.outf.write("%s:\n" % (hook_type,))
4585
 
            if hooks:
4586
 
                for hook in hooks:
4587
 
                    self.outf.write("  %s\n" %
4588
 
                                    (branch_hooks.get_hook_name(hook),))
 
5764
            info = branch._get_all_reference_info().iteritems()
 
5765
            self._display_reference_info(tree, branch, info)
 
5766
        else:
 
5767
            file_id = tree.path2id(path)
 
5768
            if file_id is None:
 
5769
                raise errors.NotVersionedError(path)
 
5770
            if location is None:
 
5771
                info = [(file_id, branch.get_reference_info(file_id))]
 
5772
                self._display_reference_info(tree, branch, info)
4589
5773
            else:
4590
 
                self.outf.write("  <no hooks installed>\n")
4591
 
 
4592
 
 
4593
 
def _create_prefix(cur_transport):
4594
 
    needed = [cur_transport]
4595
 
    # Recurse upwards until we can create a directory successfully
4596
 
    while True:
4597
 
        new_transport = cur_transport.clone('..')
4598
 
        if new_transport.base == cur_transport.base:
4599
 
            raise errors.BzrCommandError(
4600
 
                "Failed to create path prefix for %s."
4601
 
                % cur_transport.base)
4602
 
        try:
4603
 
            new_transport.mkdir('.')
4604
 
        except errors.NoSuchFile:
4605
 
            needed.append(new_transport)
4606
 
            cur_transport = new_transport
4607
 
        else:
4608
 
            break
4609
 
    # Now we only need to create child directories
4610
 
    while needed:
4611
 
        cur_transport = needed.pop()
4612
 
        cur_transport.ensure_base()
 
5774
                branch.set_reference_info(file_id, path, location)
 
5775
 
 
5776
    def _display_reference_info(self, tree, branch, info):
 
5777
        ref_list = []
 
5778
        for file_id, (path, location) in info:
 
5779
            try:
 
5780
                path = tree.id2path(file_id)
 
5781
            except errors.NoSuchId:
 
5782
                pass
 
5783
            ref_list.append((path, location))
 
5784
        for path, location in sorted(ref_list):
 
5785
            self.outf.write('%s %s\n' % (path, location))
4613
5786
 
4614
5787
 
4615
5788
# these get imported and then picked up by the scan for cmd_*
4616
5789
# TODO: Some more consistent way to split command definitions across files;
4617
 
# we do need to load at least some information about them to know of 
 
5790
# we do need to load at least some information about them to know of
4618
5791
# aliases.  ideally we would avoid loading the implementation until the
4619
5792
# details were needed.
4620
5793
from bzrlib.cmd_version_info import cmd_version_info
4622
5795
from bzrlib.bundle.commands import (
4623
5796
    cmd_bundle_info,
4624
5797
    )
 
5798
from bzrlib.foreign import cmd_dpush
4625
5799
from bzrlib.sign_my_commits import cmd_sign_my_commits
4626
5800
from bzrlib.weave_commands import cmd_versionedfile_list, \
4627
5801
        cmd_weave_plan_merge, cmd_weave_merge_text