~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Robert Collins
  • Date: 2009-08-25 21:09:17 UTC
  • mto: This revision was merged to the branch mainline in revision 4650.
  • Revision ID: robertc@robertcollins.net-20090825210917-dq2i8k6n4z63pneh
Support shelve and unshelve on windows - bug 305006.

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
2319
3043
                        specific_files=selected_list,
2320
3044
                        allow_pointless=unchanged, strict=strict, local=local,
2321
3045
                        reporter=None, verbose=verbose, revprops=properties,
2322
 
                        author=author,
 
3046
                        authors=author,
2323
3047
                        exclude=safe_relpath_files(tree, exclude))
2324
3048
        except PointlessCommit:
2325
3049
            # FIXME: This should really happen before the file is read in;
2326
3050
            # perhaps prepare the commit; get the message; then actually commit
2327
 
            raise errors.BzrCommandError("no changes to commit."
2328
 
                              " use --unchanged to commit anyhow")
 
3051
            raise errors.BzrCommandError("No changes to commit."
 
3052
                              " Use --unchanged to commit anyhow.")
2329
3053
        except ConflictsInTree:
2330
3054
            raise errors.BzrCommandError('Conflicts detected in working '
2331
3055
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
2349
3073
    The working tree and branch checks will only give output if a problem is
2350
3074
    detected. The output fields of the repository check are:
2351
3075
 
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.
 
3076
    revisions
 
3077
        This is just the number of revisions checked.  It doesn't
 
3078
        indicate a problem.
 
3079
 
 
3080
    versionedfiles
 
3081
        This is just the number of versionedfiles checked.  It
 
3082
        doesn't indicate a problem.
 
3083
 
 
3084
    unreferenced ancestors
 
3085
        Texts that are ancestors of other texts, but
 
3086
        are not properly referenced by the revision ancestry.  This is a
 
3087
        subtle problem that Bazaar can work around.
 
3088
 
 
3089
    unique file texts
 
3090
        This is the total number of unique file contents
 
3091
        seen in the checked revisions.  It does not indicate a problem.
 
3092
 
 
3093
    repeated file texts
 
3094
        This is the total number of repeated texts seen
 
3095
        in the checked revisions.  Texts can be repeated when their file
 
3096
        entries are modified, but the file contents are not.  It does not
 
3097
        indicate a problem.
2365
3098
 
2366
3099
    If no restrictions are specified, all Bazaar data that is found at the given
2367
3100
    location will be checked.
2415
3148
                    RegistryOption('format',
2416
3149
                        help='Upgrade to a specific format.  See "bzr help'
2417
3150
                             ' formats" for details.',
2418
 
                        registry=bzrdir.format_registry,
2419
 
                        converter=bzrdir.format_registry.make_bzrdir,
 
3151
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3152
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2420
3153
                        value_switches=True, title='Branch format'),
2421
3154
                    ]
2422
3155
 
2423
3156
    def run(self, url='.', format=None):
2424
3157
        from bzrlib.upgrade import upgrade
2425
 
        if format is None:
2426
 
            format = bzrdir.format_registry.make_bzrdir('default')
2427
3158
        upgrade(url, format)
2428
3159
 
2429
3160
 
2430
3161
class cmd_whoami(Command):
2431
3162
    """Show or set bzr user id.
2432
 
    
 
3163
 
2433
3164
    :Examples:
2434
3165
        Show the email of the current user::
2435
3166
 
2447
3178
                    ]
2448
3179
    takes_args = ['name?']
2449
3180
    encoding_type = 'replace'
2450
 
    
 
3181
 
2451
3182
    @display_command
2452
3183
    def run(self, email=False, branch=False, name=None):
2453
3184
        if name is None:
2468
3199
        except errors.NoEmailInUsername, e:
2469
3200
            warning('"%s" does not seem to contain an email address.  '
2470
3201
                    'This is allowed, but not recommended.', name)
2471
 
        
 
3202
 
2472
3203
        # use global config unless --branch given
2473
3204
        if branch:
2474
3205
            c = Branch.open_containing('.')[0].get_config()
2478
3209
 
2479
3210
 
2480
3211
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.  
 
3212
    """Print or set the branch nickname.
 
3213
 
 
3214
    If unset, the tree root directory name is used as the nickname.
 
3215
    To print the current nickname, execute with no argument.
 
3216
 
 
3217
    Bound branches use the nickname of its master branch unless it is set
 
3218
    locally.
2485
3219
    """
2486
3220
 
2487
3221
    _see_also = ['info']
2570
3304
 
2571
3305
class cmd_selftest(Command):
2572
3306
    """Run internal test suite.
2573
 
    
 
3307
 
2574
3308
    If arguments are given, they are regular expressions that say which tests
2575
3309
    should run.  Tests matching any expression are run, and other tests are
2576
3310
    not run.
2599
3333
    modified by plugins will not be tested, and tests provided by plugins will
2600
3334
    not be run.
2601
3335
 
2602
 
    Tests that need working space on disk use a common temporary directory, 
 
3336
    Tests that need working space on disk use a common temporary directory,
2603
3337
    typically inside $TMPDIR or /tmp.
2604
3338
 
2605
3339
    :Examples:
2644
3378
                     Option('lsprof-timed',
2645
3379
                            help='Generate lsprof output for benchmarked'
2646
3380
                                 ' sections of code.'),
 
3381
                     Option('lsprof-tests',
 
3382
                            help='Generate lsprof output for each test.'),
2647
3383
                     Option('cache-dir', type=str,
2648
3384
                            help='Cache intermediate benchmark output in this '
2649
3385
                                 'directory.'),
2653
3389
                            ),
2654
3390
                     Option('list-only',
2655
3391
                            help='List the tests instead of running them.'),
 
3392
                     RegistryOption('parallel',
 
3393
                        help="Run the test suite in parallel.",
 
3394
                        lazy_registry=('bzrlib.tests', 'parallel_registry'),
 
3395
                        value_switches=False,
 
3396
                        ),
2656
3397
                     Option('randomize', type=str, argname="SEED",
2657
3398
                            help='Randomize the order of tests using the given'
2658
3399
                                 ' seed or "now" for the current time.'),
2660
3401
                            short_name='x',
2661
3402
                            help='Exclude tests that match this regular'
2662
3403
                                 ' expression.'),
 
3404
                     Option('subunit',
 
3405
                        help='Output test progress via subunit.'),
2663
3406
                     Option('strict', help='Fail on missing dependencies or '
2664
3407
                            'known failures.'),
2665
3408
                     Option('load-list', type=str, argname='TESTLISTFILE',
2673
3416
                     ]
2674
3417
    encoding_type = 'replace'
2675
3418
 
 
3419
    def __init__(self):
 
3420
        Command.__init__(self)
 
3421
        self.additional_selftest_args = {}
 
3422
 
2676
3423
    def run(self, testspecs_list=None, verbose=False, one=False,
2677
3424
            transport=None, benchmark=None,
2678
3425
            lsprof_timed=None, cache_dir=None,
2679
3426
            first=False, list_only=False,
2680
3427
            randomize=None, exclude=None, strict=False,
2681
 
            load_list=None, debugflag=None, starting_with=None):
2682
 
        import bzrlib.ui
 
3428
            load_list=None, debugflag=None, starting_with=None, subunit=False,
 
3429
            parallel=None, lsprof_tests=False):
2683
3430
        from bzrlib.tests import selftest
2684
3431
        import bzrlib.benchmarks as benchmarks
2685
3432
        from bzrlib.benchmarks import tree_creator
2689
3436
 
2690
3437
        if cache_dir is not None:
2691
3438
            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
3439
        if testspecs_list is not None:
2701
3440
            pattern = '|'.join(testspecs_list)
2702
3441
        else:
2703
3442
            pattern = ".*"
 
3443
        if subunit:
 
3444
            try:
 
3445
                from bzrlib.tests import SubUnitBzrRunner
 
3446
            except ImportError:
 
3447
                raise errors.BzrCommandError("subunit not available. subunit "
 
3448
                    "needs to be installed to use --subunit.")
 
3449
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
 
3450
        if parallel:
 
3451
            self.additional_selftest_args.setdefault(
 
3452
                'suite_decorators', []).append(parallel)
2704
3453
        if benchmark:
2705
3454
            test_suite_factory = benchmarks.test_suite
2706
3455
            # Unless user explicitly asks for quiet, be verbose in benchmarks
2711
3460
            test_suite_factory = None
2712
3461
            benchfile = None
2713
3462
        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
 
                              )
 
3463
            selftest_kwargs = {"verbose": verbose,
 
3464
                              "pattern": pattern,
 
3465
                              "stop_on_failure": one,
 
3466
                              "transport": transport,
 
3467
                              "test_suite_factory": test_suite_factory,
 
3468
                              "lsprof_timed": lsprof_timed,
 
3469
                              "lsprof_tests": lsprof_tests,
 
3470
                              "bench_history": benchfile,
 
3471
                              "matching_tests_first": first,
 
3472
                              "list_only": list_only,
 
3473
                              "random_seed": randomize,
 
3474
                              "exclude_pattern": exclude,
 
3475
                              "strict": strict,
 
3476
                              "load_list": load_list,
 
3477
                              "debug_flags": debugflag,
 
3478
                              "starting_with": starting_with
 
3479
                              }
 
3480
            selftest_kwargs.update(self.additional_selftest_args)
 
3481
            result = selftest(**selftest_kwargs)
2730
3482
        finally:
2731
3483
            if benchfile is not None:
2732
3484
                benchfile.close()
2733
 
        if result:
2734
 
            note('tests passed')
2735
 
        else:
2736
 
            note('tests failed')
2737
3485
        return int(not result)
2738
3486
 
2739
3487
 
2770
3518
    #       merging only part of the history.
2771
3519
    takes_args = ['branch', 'other']
2772
3520
    hidden = True
2773
 
    
 
3521
 
2774
3522
    @display_command
2775
3523
    def run(self, branch, other):
2776
3524
        from bzrlib.revision import ensure_null
2777
 
        
 
3525
 
2778
3526
        branch1 = Branch.open_containing(branch)[0]
2779
3527
        branch2 = Branch.open_containing(other)[0]
2780
3528
        branch1.lock_read()
2796
3544
 
2797
3545
class cmd_merge(Command):
2798
3546
    """Perform a three-way merge.
2799
 
    
 
3547
 
2800
3548
    The source of the merge can be specified either in the form of a branch,
2801
3549
    or in the form of a path to a file containing a merge directive generated
2802
3550
    with bzr send. If neither is specified, the default is the upstream branch
2812
3560
    By default, bzr will try to merge in all new work from the other
2813
3561
    branch, automatically determining an appropriate base.  If this
2814
3562
    fails, you may need to give an explicit base.
2815
 
    
 
3563
 
2816
3564
    Merge will do its best to combine the changes in two branches, but there
2817
3565
    are some kinds of problems only a human can fix.  When it encounters those,
2818
3566
    it will mark a conflict.  A conflict means that you need to fix something,
2828
3576
    The results of the merge are placed into the destination working
2829
3577
    directory, where they can be reviewed (with bzr diff), tested, and then
2830
3578
    committed to record the result of the merge.
2831
 
    
 
3579
 
2832
3580
    merge refuses to run if there are any uncommitted changes, unless
2833
3581
    --force is given.
2834
3582
 
 
3583
    To select only some changes to merge, use "merge -i", which will prompt
 
3584
    you to apply each diff hunk and file change, similar to "shelve".
 
3585
 
2835
3586
    :Examples:
2836
3587
        To merge the latest revision from bzr.dev::
2837
3588
 
2845
3596
 
2846
3597
            bzr merge -r 81..82 ../bzr.dev
2847
3598
 
2848
 
        To apply a merge directive contained in in /tmp/merge:
 
3599
        To apply a merge directive contained in /tmp/merge:
2849
3600
 
2850
3601
            bzr merge /tmp/merge
2851
3602
    """
2852
3603
 
2853
3604
    encoding_type = 'exact'
2854
 
    _see_also = ['update', 'remerge', 'status-flags']
 
3605
    _see_also = ['update', 'remerge', 'status-flags', 'send']
2855
3606
    takes_args = ['location?']
2856
3607
    takes_options = [
2857
3608
        'change',
2875
3626
               short_name='d',
2876
3627
               type=unicode,
2877
3628
               ),
2878
 
        Option('preview', help='Instead of merging, show a diff of the merge.')
 
3629
        Option('preview', help='Instead of merging, show a diff of the'
 
3630
               ' merge.'),
 
3631
        Option('interactive', help='Select changes interactively.',
 
3632
            short_name='i')
2879
3633
    ]
2880
3634
 
2881
3635
    def run(self, location=None, revision=None, force=False,
2882
 
            merge_type=None, show_base=False, reprocess=False, remember=False,
 
3636
            merge_type=None, show_base=False, reprocess=None, remember=False,
2883
3637
            uncommitted=False, pull=False,
2884
3638
            directory=None,
2885
3639
            preview=False,
 
3640
            interactive=False,
2886
3641
            ):
2887
3642
        if merge_type is None:
2888
3643
            merge_type = _mod_merge.Merge3Merger
2893
3648
        allow_pending = True
2894
3649
        verified = 'inapplicable'
2895
3650
        tree = WorkingTree.open_containing(directory)[0]
 
3651
 
 
3652
        # die as quickly as possible if there are uncommitted changes
 
3653
        try:
 
3654
            basis_tree = tree.revision_tree(tree.last_revision())
 
3655
        except errors.NoSuchRevision:
 
3656
            basis_tree = tree.basis_tree()
 
3657
        if not force:
 
3658
            if tree.has_changes(basis_tree):
 
3659
                raise errors.UncommittedChanges(tree)
 
3660
 
 
3661
        view_info = _get_view_info_for_change_reporter(tree)
2896
3662
        change_reporter = delta._ChangeReporter(
2897
 
            unversioned_filter=tree.is_ignored)
 
3663
            unversioned_filter=tree.is_ignored, view_info=view_info)
2898
3664
        cleanups = []
2899
3665
        try:
2900
3666
            pb = ui.ui_factory.nested_progress_bar()
2922
3688
                if revision is not None and len(revision) > 0:
2923
3689
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
2924
3690
                        ' --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)
 
3691
                merger = self.get_merger_from_uncommitted(tree, location, pb,
 
3692
                                                          cleanups)
2929
3693
                allow_pending = False
2930
 
                if other_path != '':
2931
 
                    merger.interesting_files = [other_path]
2932
3694
 
2933
3695
            if merger is None:
2934
3696
                merger, allow_pending = self._get_merger_from_branch(tree,
2950
3712
                                       merger.other_rev_id)
2951
3713
                    result.report(self.outf)
2952
3714
                    return 0
2953
 
            merger.check_basis(not force)
 
3715
            merger.check_basis(False)
2954
3716
            if preview:
2955
 
                return self._do_preview(merger)
 
3717
                return self._do_preview(merger, cleanups)
 
3718
            elif interactive:
 
3719
                return self._do_interactive(merger, cleanups)
2956
3720
            else:
2957
3721
                return self._do_merge(merger, change_reporter, allow_pending,
2958
3722
                                      verified)
2960
3724
            for cleanup in reversed(cleanups):
2961
3725
                cleanup()
2962
3726
 
2963
 
    def _do_preview(self, merger):
2964
 
        from bzrlib.diff import show_diff_trees
 
3727
    def _get_preview(self, merger, cleanups):
2965
3728
        tree_merger = merger.make_merger()
2966
3729
        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()
 
3730
        cleanups.append(tt.finalize)
 
3731
        result_tree = tt.get_preview_tree()
 
3732
        return result_tree
 
3733
 
 
3734
    def _do_preview(self, merger, cleanups):
 
3735
        from bzrlib.diff import show_diff_trees
 
3736
        result_tree = self._get_preview(merger, cleanups)
 
3737
        show_diff_trees(merger.this_tree, result_tree, self.outf,
 
3738
                        old_label='', new_label='')
2973
3739
 
2974
3740
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
2975
3741
        merger.change_reporter = change_reporter
2983
3749
        else:
2984
3750
            return 0
2985
3751
 
 
3752
    def _do_interactive(self, merger, cleanups):
 
3753
        """Perform an interactive merge.
 
3754
 
 
3755
        This works by generating a preview tree of the merge, then using
 
3756
        Shelver to selectively remove the differences between the working tree
 
3757
        and the preview tree.
 
3758
        """
 
3759
        from bzrlib import shelf_ui
 
3760
        result_tree = self._get_preview(merger, cleanups)
 
3761
        writer = bzrlib.option.diff_writer_registry.get()
 
3762
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
 
3763
                                   reporter=shelf_ui.ApplyReporter(),
 
3764
                                   diff_writer=writer(sys.stdout))
 
3765
        shelver.run()
 
3766
 
2986
3767
    def sanity_check_merger(self, merger):
2987
3768
        if (merger.show_base and
2988
3769
            not merger.merge_type is _mod_merge.Merge3Merger):
2989
3770
            raise errors.BzrCommandError("Show-base is not supported for this"
2990
3771
                                         " merge type. %s" % merger.merge_type)
 
3772
        if merger.reprocess is None:
 
3773
            if merger.show_base:
 
3774
                merger.reprocess = False
 
3775
            else:
 
3776
                # Use reprocess if the merger supports it
 
3777
                merger.reprocess = merger.merge_type.supports_reprocess
2991
3778
        if merger.reprocess and not merger.merge_type.supports_reprocess:
2992
3779
            raise errors.BzrCommandError("Conflict reduction is not supported"
2993
3780
                                         " for merge type %s." %
3017
3804
            base_branch, base_path = Branch.open_containing(base_loc,
3018
3805
                possible_transports)
3019
3806
        # Find the revision ids
3020
 
        if revision is None or len(revision) < 1 or revision[-1] is None:
 
3807
        other_revision_id = None
 
3808
        base_revision_id = None
 
3809
        if revision is not None:
 
3810
            if len(revision) >= 1:
 
3811
                other_revision_id = revision[-1].as_revision_id(other_branch)
 
3812
            if len(revision) == 2:
 
3813
                base_revision_id = revision[0].as_revision_id(base_branch)
 
3814
        if other_revision_id is None:
3021
3815
            other_revision_id = _mod_revision.ensure_null(
3022
3816
                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
3817
        # Remember where we merge from
3031
3818
        if ((remember or tree.branch.get_submit_branch() is None) and
3032
3819
             user_location is not None):
3041
3828
            allow_pending = True
3042
3829
        return merger, allow_pending
3043
3830
 
 
3831
    def get_merger_from_uncommitted(self, tree, location, pb, cleanups):
 
3832
        """Get a merger for uncommitted changes.
 
3833
 
 
3834
        :param tree: The tree the merger should apply to.
 
3835
        :param location: The location containing uncommitted changes.
 
3836
        :param pb: The progress bar to use for showing progress.
 
3837
        :param cleanups: A list of operations to perform to clean up the
 
3838
            temporary directories, unfinalized objects, etc.
 
3839
        """
 
3840
        location = self._select_branch_location(tree, location)[0]
 
3841
        other_tree, other_path = WorkingTree.open_containing(location)
 
3842
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
 
3843
        if other_path != '':
 
3844
            merger.interesting_files = [other_path]
 
3845
        return merger
 
3846
 
3044
3847
    def _select_branch_location(self, tree, user_location, revision=None,
3045
3848
                                index=None):
3046
3849
        """Select a branch location, according to possible inputs.
3093
3896
    """Redo a merge.
3094
3897
 
3095
3898
    Use this if you want to try a different merge technique while resolving
3096
 
    conflicts.  Some merge techniques are better than others, and remerge 
 
3899
    conflicts.  Some merge techniques are better than others, and remerge
3097
3900
    lets you try different ones on different files.
3098
3901
 
3099
3902
    The options for remerge have the same meaning and defaults as the ones for
3103
3906
    :Examples:
3104
3907
        Re-do the merge of all conflicted files, and show the base text in
3105
3908
        conflict regions, in addition to the usual THIS and OTHER texts::
3106
 
      
 
3909
 
3107
3910
            bzr remerge --show-base
3108
3911
 
3109
3912
        Re-do the merge of "foobar", using the weave merge algorithm, with
3110
3913
        additional processing to reduce the size of conflict regions::
3111
 
      
 
3914
 
3112
3915
            bzr remerge --merge-type weave --reprocess foobar
3113
3916
    """
3114
3917
    takes_args = ['file*']
3144
3947
                    interesting_ids.add(file_id)
3145
3948
                    if tree.kind(file_id) != "directory":
3146
3949
                        continue
3147
 
                    
 
3950
 
3148
3951
                    for name, ie in tree.inventory.iter_entries(file_id):
3149
3952
                        interesting_ids.add(ie.file_id)
3150
3953
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3199
4002
    merge instead.  For example, "merge . --revision -2..-3" will remove the
3200
4003
    changes introduced by -2, without affecting the changes introduced by -1.
3201
4004
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3202
 
    
 
4005
 
3203
4006
    By default, any files that have been manually changed will be backed up
3204
4007
    first.  (Files changed only by merge are not backed up.)  Backup files have
3205
4008
    '.~#~' appended to their name, where # is a number.
3234
4037
    def run(self, revision=None, no_backup=False, file_list=None,
3235
4038
            forget_merges=None):
3236
4039
        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)
 
4040
        tree.lock_write()
 
4041
        try:
 
4042
            if forget_merges:
 
4043
                tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4044
            else:
 
4045
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4046
        finally:
 
4047
            tree.unlock()
3241
4048
 
3242
4049
    @staticmethod
3243
4050
    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)
 
4051
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3250
4052
        pb = ui.ui_factory.nested_progress_bar()
3251
4053
        try:
3252
 
            tree.revert(file_list,
3253
 
                        tree.branch.repository.revision_tree(rev_id),
3254
 
                        not no_backup, pb, report_changes=True)
 
4054
            tree.revert(file_list, rev_tree, not no_backup, pb,
 
4055
                report_changes=True)
3255
4056
        finally:
3256
4057
            pb.finished()
3257
4058
 
3276
4077
            ]
3277
4078
    takes_args = ['topic?']
3278
4079
    aliases = ['?', '--help', '-?', '-h']
3279
 
    
 
4080
 
3280
4081
    @display_command
3281
4082
    def run(self, topic=None, long=False):
3282
4083
        import bzrlib.help
3293
4094
    takes_args = ['context?']
3294
4095
    aliases = ['s-c']
3295
4096
    hidden = True
3296
 
    
 
4097
 
3297
4098
    @display_command
3298
4099
    def run(self, context=None):
3299
4100
        import shellcomplete
3302
4103
 
3303
4104
class cmd_missing(Command):
3304
4105
    """Show unmerged/unpulled revisions between two branches.
3305
 
    
 
4106
 
3306
4107
    OTHER_BRANCH may be local or remote.
 
4108
 
 
4109
    To filter on a range of revisions, you can use the command -r begin..end
 
4110
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
4111
    also valid.
 
4112
 
 
4113
    :Examples:
 
4114
 
 
4115
        Determine the missing revisions between this and the branch at the
 
4116
        remembered pull location::
 
4117
 
 
4118
            bzr missing
 
4119
 
 
4120
        Determine the missing revisions between this and another branch::
 
4121
 
 
4122
            bzr missing http://server/branch
 
4123
 
 
4124
        Determine the missing revisions up to a specific revision on the other
 
4125
        branch::
 
4126
 
 
4127
            bzr missing -r ..-10
 
4128
 
 
4129
        Determine the missing revisions up to a specific revision on this
 
4130
        branch::
 
4131
 
 
4132
            bzr missing --my-revision ..-10
3307
4133
    """
3308
4134
 
3309
4135
    _see_also = ['merge', 'pull']
3310
4136
    takes_args = ['other_branch?']
3311
4137
    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
 
            ]
 
4138
        Option('reverse', 'Reverse the order of revisions.'),
 
4139
        Option('mine-only',
 
4140
               'Display changes in the local branch only.'),
 
4141
        Option('this' , 'Same as --mine-only.'),
 
4142
        Option('theirs-only',
 
4143
               'Display changes in the remote branch only.'),
 
4144
        Option('other', 'Same as --theirs-only.'),
 
4145
        'log-format',
 
4146
        'show-ids',
 
4147
        'verbose',
 
4148
        custom_help('revision',
 
4149
             help='Filter on other branch revisions (inclusive). '
 
4150
                'See "help revisionspec" for details.'),
 
4151
        Option('my-revision',
 
4152
            type=_parse_revision_str,
 
4153
            help='Filter on local branch revisions (inclusive). '
 
4154
                'See "help revisionspec" for details.'),
 
4155
        Option('include-merges',
 
4156
               'Show all revisions in addition to the mainline ones.'),
 
4157
        ]
3323
4158
    encoding_type = 'replace'
3324
4159
 
3325
4160
    @display_command
3326
4161
    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):
 
4162
            theirs_only=False,
 
4163
            log_format=None, long=False, short=False, line=False,
 
4164
            show_ids=False, verbose=False, this=False, other=False,
 
4165
            include_merges=False, revision=None, my_revision=None):
3329
4166
        from bzrlib.missing import find_unmerged, iter_log_revisions
 
4167
        def message(s):
 
4168
            if not is_quiet():
 
4169
                self.outf.write(s)
3330
4170
 
3331
4171
        if this:
3332
4172
            mine_only = this
3350
4190
                                             " or specified.")
3351
4191
            display_url = urlutils.unescape_for_display(parent,
3352
4192
                                                        self.outf.encoding)
3353
 
            self.outf.write("Using saved parent location: "
 
4193
            message("Using saved parent location: "
3354
4194
                    + display_url + "\n")
3355
4195
 
3356
4196
        remote_branch = Branch.open(other_branch)
3357
4197
        if remote_branch.base == local_branch.base:
3358
4198
            remote_branch = local_branch
 
4199
 
 
4200
        local_revid_range = _revision_range_to_revid_range(
 
4201
            _get_revision_range(my_revision, local_branch,
 
4202
                self.name()))
 
4203
 
 
4204
        remote_revid_range = _revision_range_to_revid_range(
 
4205
            _get_revision_range(revision,
 
4206
                remote_branch, self.name()))
 
4207
 
3359
4208
        local_branch.lock_read()
3360
4209
        try:
3361
4210
            remote_branch.lock_read()
3362
4211
            try:
3363
4212
                local_extra, remote_extra = find_unmerged(
3364
 
                    local_branch, remote_branch, restrict)
 
4213
                    local_branch, remote_branch, restrict,
 
4214
                    backward=not reverse,
 
4215
                    include_merges=include_merges,
 
4216
                    local_revid_range=local_revid_range,
 
4217
                    remote_revid_range=remote_revid_range)
3365
4218
 
3366
4219
                if log_format is None:
3367
4220
                    registry = log.log_formatter_registry
3369
4222
                lf = log_format(to_file=self.outf,
3370
4223
                                show_ids=show_ids,
3371
4224
                                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
4225
 
3378
4226
                status_code = 0
3379
4227
                if local_extra and not theirs_only:
3380
 
                    self.outf.write("You have %d extra revision(s):\n" %
3381
 
                                    len(local_extra))
 
4228
                    message("You have %d extra revision(s):\n" %
 
4229
                        len(local_extra))
3382
4230
                    for revision in iter_log_revisions(local_extra,
3383
4231
                                        local_branch.repository,
3384
4232
                                        verbose):
3390
4238
 
3391
4239
                if remote_extra and not mine_only:
3392
4240
                    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))
 
4241
                        message("\n\n\n")
 
4242
                    message("You are missing %d revision(s):\n" %
 
4243
                        len(remote_extra))
3396
4244
                    for revision in iter_log_revisions(remote_extra,
3397
4245
                                        remote_branch.repository,
3398
4246
                                        verbose):
3401
4249
 
3402
4250
                if mine_only and not local_extra:
3403
4251
                    # We checked local, and found nothing extra
3404
 
                    self.outf.write('This branch is up to date.\n')
 
4252
                    message('This branch is up to date.\n')
3405
4253
                elif theirs_only and not remote_extra:
3406
4254
                    # We checked remote, and found nothing extra
3407
 
                    self.outf.write('Other branch is up to date.\n')
 
4255
                    message('Other branch is up to date.\n')
3408
4256
                elif not (mine_only or theirs_only or local_extra or
3409
4257
                          remote_extra):
3410
4258
                    # We checked both branches, and neither one had extra
3411
4259
                    # revisions
3412
 
                    self.outf.write("Branches are up to date.\n")
 
4260
                    message("Branches are up to date.\n")
3413
4261
            finally:
3414
4262
                remote_branch.unlock()
3415
4263
        finally:
3443
4291
 
3444
4292
class cmd_plugins(Command):
3445
4293
    """List the installed plugins.
3446
 
    
 
4294
 
3447
4295
    This command displays the list of installed plugins including
3448
4296
    version of plugin and a short description of each.
3449
4297
 
3526
4374
    This prints out the given file with an annotation on the left side
3527
4375
    indicating which revision, author and date introduced the change.
3528
4376
 
3529
 
    If the origin is the same for a run of consecutive lines, it is 
 
4377
    If the origin is the same for a run of consecutive lines, it is
3530
4378
    shown only at the top, unless the --all option is given.
3531
4379
    """
3532
4380
    # TODO: annotate directories; showing when each file was last changed
3533
 
    # TODO: if the working copy is modified, show annotations on that 
 
4381
    # TODO: if the working copy is modified, show annotations on that
3534
4382
    #       with new uncommitted lines marked
3535
4383
    aliases = ['ann', 'blame', 'praise']
3536
4384
    takes_args = ['filename']
3544
4392
    @display_command
3545
4393
    def run(self, filename, all=False, long=False, revision=None,
3546
4394
            show_ids=False):
3547
 
        from bzrlib.annotate import annotate_file
 
4395
        from bzrlib.annotate import annotate_file, annotate_file_tree
3548
4396
        wt, branch, relpath = \
3549
4397
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3550
4398
        if wt is not None:
3552
4400
        else:
3553
4401
            branch.lock_read()
3554
4402
        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)
 
4403
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
3562
4404
            if wt is not None:
3563
4405
                file_id = wt.path2id(relpath)
3564
4406
            else:
3566
4408
            if file_id is None:
3567
4409
                raise errors.NotVersionedError(filename)
3568
4410
            file_version = tree.inventory[file_id].revision
3569
 
            annotate_file(branch, file_version, file_id, long, all, self.outf,
3570
 
                          show_ids=show_ids)
 
4411
            if wt is not None and revision is None:
 
4412
                # If there is a tree and we're not annotating historical
 
4413
                # versions, annotate the working tree's content.
 
4414
                annotate_file_tree(wt, file_id, self.outf, long, all,
 
4415
                    show_ids=show_ids)
 
4416
            else:
 
4417
                annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4418
                              show_ids=show_ids)
3571
4419
        finally:
3572
4420
            if wt is not None:
3573
4421
                wt.unlock()
3582
4430
    hidden = True # is this right ?
3583
4431
    takes_args = ['revision_id*']
3584
4432
    takes_options = ['revision']
3585
 
    
 
4433
 
3586
4434
    def run(self, revision_id_list=None, revision=None):
3587
4435
        if revision_id_list is not None and revision is not None:
3588
4436
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3648
4496
 
3649
4497
    Once converted into a checkout, commits must succeed on the master branch
3650
4498
    before they will be applied to the local branch.
 
4499
 
 
4500
    Bound branches use the nickname of its master branch unless it is set
 
4501
    locally, in which case binding will update the the local nickname to be
 
4502
    that of the master.
3651
4503
    """
3652
4504
 
3653
4505
    _see_also = ['checkouts', 'unbind']
3672
4524
        except errors.DivergedBranches:
3673
4525
            raise errors.BzrCommandError('These branches have diverged.'
3674
4526
                                         ' Try merging, and then bind again.')
 
4527
        if b.get_config().has_explicit_nickname():
 
4528
            b.nick = b_other.nick
3675
4529
 
3676
4530
 
3677
4531
class cmd_unbind(Command):
3812
4666
    holding the lock has been stopped.
3813
4667
 
3814
4668
    You can get information on what locks are open via the 'bzr info' command.
3815
 
    
 
4669
 
3816
4670
    :Examples:
3817
4671
        bzr break-lock
3818
4672
    """
3826
4680
            control.break_lock()
3827
4681
        except NotImplementedError:
3828
4682
            pass
3829
 
        
 
4683
 
3830
4684
 
3831
4685
class cmd_wait_until_signalled(Command):
3832
4686
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3850
4704
    takes_options = [
3851
4705
        Option('inet',
3852
4706
               help='Serve on stdin/out for use from inetd or sshd.'),
 
4707
        RegistryOption('protocol', 
 
4708
               help="Protocol to serve.", 
 
4709
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
 
4710
               value_switches=True),
3853
4711
        Option('port',
3854
4712
               help='Listen for connections on nominated port of the form '
3855
4713
                    '[hostname:]portnumber.  Passing 0 as the port number will '
3856
 
                    'result in a dynamically allocated port.  The default port is '
3857
 
                    '4155.',
 
4714
                    'result in a dynamically allocated port.  The default port '
 
4715
                    'depends on the protocol.',
3858
4716
               type=str),
3859
4717
        Option('directory',
3860
4718
               help='Serve contents of this directory.',
3866
4724
                ),
3867
4725
        ]
3868
4726
 
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
 
4727
    def get_host_and_port(self, port):
 
4728
        """Return the host and port to run the smart server on.
 
4729
 
 
4730
        If 'port' is None, None will be returned for the host and port.
 
4731
 
 
4732
        If 'port' has a colon in it, the string before the colon will be
 
4733
        interpreted as the host.
 
4734
 
 
4735
        :param port: A string of the port to run the server on.
 
4736
        :return: A tuple of (host, port), where 'host' is a host name or IP,
 
4737
            and port is an integer TCP/IP port.
 
4738
        """
 
4739
        host = None
 
4740
        if port is not None:
 
4741
            if ':' in port:
 
4742
                host, port = port.split(':')
 
4743
            port = int(port)
 
4744
        return host, port
 
4745
 
 
4746
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
 
4747
            protocol=None):
 
4748
        from bzrlib.transport import get_transport, transport_server_registry
3874
4749
        if directory is None:
3875
4750
            directory = os.getcwd()
 
4751
        if protocol is None:
 
4752
            protocol = transport_server_registry.get()
 
4753
        host, port = self.get_host_and_port(port)
3876
4754
        url = urlutils.local_path_to_url(directory)
3877
4755
        if not allow_writes:
3878
4756
            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
 
4757
        transport = get_transport(url)
 
4758
        protocol(transport, host, port, inet)
3909
4759
 
3910
4760
 
3911
4761
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.
 
4762
    """Combine a tree into its containing tree.
 
4763
 
 
4764
    This command requires the target tree to be in a rich-root format.
3917
4765
 
3918
4766
    The TREE argument should be an independent tree, inside another tree, but
3919
4767
    not part of it.  (Such trees can be produced by "bzr split", but also by
3922
4770
    The result is a combined tree, with the subtree no longer an independant
3923
4771
    part.  This is marked as a merge of the subtree into the containing tree,
3924
4772
    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
4773
    """
3931
4774
 
3932
4775
    _see_also = ['split']
3933
4776
    takes_args = ['tree']
3934
4777
    takes_options = [
3935
 
            Option('reference', help='Join by reference.'),
 
4778
            Option('reference', help='Join by reference.', hidden=True),
3936
4779
            ]
3937
 
    hidden = True
3938
4780
 
3939
4781
    def run(self, tree, reference=False):
3940
4782
        sub_tree = WorkingTree.open(tree)
3958
4800
            try:
3959
4801
                containing_tree.subsume(sub_tree)
3960
4802
            except errors.BadSubsumeSource, e:
3961
 
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
 
4803
                raise errors.BzrCommandError("Cannot join %s.  %s" %
3962
4804
                                             (tree, e.reason))
3963
4805
 
3964
4806
 
3974
4816
    branch.  Commits in the top-level tree will not apply to the new subtree.
3975
4817
    """
3976
4818
 
3977
 
    # join is not un-hidden yet
3978
 
    #_see_also = ['join']
 
4819
    _see_also = ['join']
3979
4820
    takes_args = ['tree']
3980
4821
 
3981
4822
    def run(self, tree):
3986
4827
        try:
3987
4828
            containing_tree.extract(sub_id)
3988
4829
        except errors.RootNotRich:
3989
 
            raise errors.UpgradeRequired(containing_tree.branch.base)
 
4830
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
3990
4831
 
3991
4832
 
3992
4833
class cmd_merge_directive(Command):
4089
4930
 
4090
4931
 
4091
4932
class cmd_send(Command):
4092
 
    """Mail or create a merge-directive for submiting changes.
 
4933
    """Mail or create a merge-directive for submitting changes.
4093
4934
 
4094
4935
    A merge directive provides many things needed for requesting merges:
4095
4936
 
4117
4958
    Mail is sent using your preferred mail program.  This should be transparent
4118
4959
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
4119
4960
    If the preferred client can't be found (or used), your editor will be used.
4120
 
    
 
4961
 
4121
4962
    To use a specific mail program, set the mail_client configuration option.
4122
4963
    (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.
 
4964
    specific clients are "claws", "evolution", "kmail", "mutt", and
 
4965
    "thunderbird"; generic options are "default", "editor", "emacsclient",
 
4966
    "mapi", and "xdg-email".  Plugins may also add supported clients.
4126
4967
 
4127
4968
    If mail is being sent, a to address is required.  This can be supplied
4128
4969
    either on the commandline, by setting the submit_to configuration
4129
 
    option in the branch itself or the child_submit_to configuration option 
 
4970
    option in the branch itself or the child_submit_to configuration option
4130
4971
    in the submit branch.
4131
4972
 
4132
4973
    Two formats are currently supported: "4" uses revision bundle format 4 and
4134
4975
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
4135
4976
    default.  "0.9" uses revision bundle format 0.9 and merge directive
4136
4977
    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.
 
4978
 
 
4979
    The merge directives created by bzr send may be applied using bzr merge or
 
4980
    bzr pull by specifying a file containing a merge directive as the location.
4139
4981
    """
4140
4982
 
4141
4983
    encoding_type = 'exact'
4160
5002
               help='Write merge directive to this file; '
4161
5003
                    'use - for stdout.',
4162
5004
               type=unicode),
 
5005
        Option('strict',
 
5006
               help='Refuse to send if there are uncommitted changes in'
 
5007
               ' the working tree, --no-strict disables the check.'),
4163
5008
        Option('mail-to', help='Mail the request to this address.',
4164
5009
               type=unicode),
4165
5010
        'revision',
4166
5011
        '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',})
 
5012
        Option('body', help='Body for the email.', type=unicode),
 
5013
        RegistryOption('format',
 
5014
                       help='Use the specified output format.',
 
5015
                       lazy_registry=('bzrlib.send', 'format_registry')),
4171
5016
        ]
4172
5017
 
4173
5018
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4174
5019
            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()
 
5020
            format=None, mail_to=None, message=None, body=None,
 
5021
            strict=None, **kwargs):
 
5022
        from bzrlib.send import send
 
5023
        return send(submit_branch, revision, public_branch, remember,
 
5024
                    format, no_bundle, no_patch, output,
 
5025
                    kwargs.get('from', '.'), mail_to, message, body,
 
5026
                    self.outf,
 
5027
                    strict=strict)
4286
5028
 
4287
5029
 
4288
5030
class cmd_bundle_revisions(cmd_send):
4289
 
 
4290
 
    """Create a merge-directive for submiting changes.
 
5031
    """Create a merge-directive for submitting changes.
4291
5032
 
4292
5033
    A merge directive provides many things needed for requesting merges:
4293
5034
 
4333
5074
               type=unicode),
4334
5075
        Option('output', short_name='o', help='Write directive to this file.',
4335
5076
               type=unicode),
 
5077
        Option('strict',
 
5078
               help='Refuse to bundle revisions if there are uncommitted'
 
5079
               ' changes in the working tree, --no-strict disables the check.'),
4336
5080
        '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',})
 
5081
        RegistryOption('format',
 
5082
                       help='Use the specified output format.',
 
5083
                       lazy_registry=('bzrlib.send', 'format_registry')),
4341
5084
        ]
4342
5085
    aliases = ['bundle']
4343
5086
 
4347
5090
 
4348
5091
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4349
5092
            no_patch=False, revision=None, remember=False, output=None,
4350
 
            format='4', **kwargs):
 
5093
            format=None, strict=None, **kwargs):
4351
5094
        if output is None:
4352
5095
            output = '-'
4353
 
        return self._run(submit_branch, revision, public_branch, remember,
 
5096
        from bzrlib.send import send
 
5097
        return send(submit_branch, revision, public_branch, remember,
4354
5098
                         format, no_bundle, no_patch, output,
4355
 
                         kwargs.get('from', '.'), None, None)
 
5099
                         kwargs.get('from', '.'), None, None, None,
 
5100
                         self.outf, strict=strict)
4356
5101
 
4357
5102
 
4358
5103
class cmd_tag(Command):
4359
5104
    """Create, remove or modify a tag naming a revision.
4360
 
    
 
5105
 
4361
5106
    Tags give human-meaningful names to revisions.  Commands that take a -r
4362
5107
    (--revision) option can be given -rtag:X, where X is any previously
4363
5108
    created tag.
4365
5110
    Tags are stored in the branch.  Tags are copied from one branch to another
4366
5111
    along when you branch, push, pull or merge.
4367
5112
 
4368
 
    It is an error to give a tag name that already exists unless you pass 
 
5113
    It is an error to give a tag name that already exists unless you pass
4369
5114
    --force, in which case the tag is moved to point to the new revision.
4370
5115
 
4371
5116
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
4437
5182
            time='Sort tags chronologically.',
4438
5183
            ),
4439
5184
        'show-ids',
 
5185
        'revision',
4440
5186
    ]
4441
5187
 
4442
5188
    @display_command
4444
5190
            directory='.',
4445
5191
            sort='alpha',
4446
5192
            show_ids=False,
 
5193
            revision=None,
4447
5194
            ):
4448
5195
        branch, relpath = Branch.open_containing(directory)
 
5196
 
4449
5197
        tags = branch.tags.get_tag_dict().items()
4450
5198
        if not tags:
4451
5199
            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 ]
 
5200
 
 
5201
        branch.lock_read()
 
5202
        try:
 
5203
            if revision:
 
5204
                graph = branch.repository.get_graph()
 
5205
                rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5206
                revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5207
                # only show revisions between revid1 and revid2 (inclusive)
 
5208
                tags = [(tag, revid) for tag, revid in tags if
 
5209
                    graph.is_between(revid, revid1, revid2)]
 
5210
            if sort == 'alpha':
 
5211
                tags.sort()
 
5212
            elif sort == 'time':
 
5213
                timestamps = {}
 
5214
                for tag, revid in tags:
 
5215
                    try:
 
5216
                        revobj = branch.repository.get_revision(revid)
 
5217
                    except errors.NoSuchRevision:
 
5218
                        timestamp = sys.maxint # place them at the end
 
5219
                    else:
 
5220
                        timestamp = revobj.timestamp
 
5221
                    timestamps[revid] = timestamp
 
5222
                tags.sort(key=lambda x: timestamps[x[1]])
 
5223
            if not show_ids:
 
5224
                # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
5225
                for index, (tag, revid) in enumerate(tags):
 
5226
                    try:
 
5227
                        revno = branch.revision_id_to_dotted_revno(revid)
 
5228
                        if isinstance(revno, tuple):
 
5229
                            revno = '.'.join(map(str, revno))
 
5230
                    except errors.NoSuchRevision:
 
5231
                        # Bad tag data/merges can lead to tagged revisions
 
5232
                        # which are not in this branch. Fail gracefully ...
 
5233
                        revno = '?'
 
5234
                    tags[index] = (tag, revno)
 
5235
        finally:
 
5236
            branch.unlock()
4470
5237
        for tag, revspec in tags:
4471
5238
            self.outf.write('%-20s %s\n' % (tag, revspec))
4472
5239
 
4487
5254
 
4488
5255
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4489
5256
    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
 
                     ]
 
5257
    takes_options = [
 
5258
        RegistryOption.from_kwargs(
 
5259
            'target_type',
 
5260
            title='Target type',
 
5261
            help='The type to reconfigure the directory to.',
 
5262
            value_switches=True, enum_switch=False,
 
5263
            branch='Reconfigure to be an unbound branch with no working tree.',
 
5264
            tree='Reconfigure to be an unbound branch with a working tree.',
 
5265
            checkout='Reconfigure to be a bound branch with a working tree.',
 
5266
            lightweight_checkout='Reconfigure to be a lightweight'
 
5267
                ' checkout (with no local history).',
 
5268
            standalone='Reconfigure to be a standalone branch '
 
5269
                '(i.e. stop using shared repository).',
 
5270
            use_shared='Reconfigure to use a shared repository.',
 
5271
            with_trees='Reconfigure repository to create '
 
5272
                'working trees on branches by default.',
 
5273
            with_no_trees='Reconfigure repository to not create '
 
5274
                'working trees on branches by default.'
 
5275
            ),
 
5276
        Option('bind-to', help='Branch to bind checkout to.', type=str),
 
5277
        Option('force',
 
5278
            help='Perform reconfiguration even if local changes'
 
5279
            ' will be lost.'),
 
5280
        Option('stacked-on',
 
5281
            help='Reconfigure a branch to be stacked on another branch.',
 
5282
            type=unicode,
 
5283
            ),
 
5284
        Option('unstacked',
 
5285
            help='Reconfigure a branch to be unstacked.  This '
 
5286
                'may require copying substantial data into it.',
 
5287
            ),
 
5288
        ]
4511
5289
 
4512
 
    def run(self, location=None, target_type=None, bind_to=None, force=False):
 
5290
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5291
            stacked_on=None,
 
5292
            unstacked=None):
4513
5293
        directory = bzrdir.BzrDir.open(location)
 
5294
        if stacked_on and unstacked:
 
5295
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5296
        elif stacked_on is not None:
 
5297
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
 
5298
        elif unstacked:
 
5299
            reconfigure.ReconfigureUnstacked().apply(directory)
 
5300
        # At the moment you can use --stacked-on and a different
 
5301
        # reconfiguration shape at the same time; there seems no good reason
 
5302
        # to ban it.
4514
5303
        if target_type is None:
4515
 
            raise errors.BzrCommandError('No target configuration specified')
 
5304
            if stacked_on or unstacked:
 
5305
                return
 
5306
            else:
 
5307
                raise errors.BzrCommandError('No target configuration '
 
5308
                    'specified')
4516
5309
        elif target_type == 'branch':
4517
5310
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4518
5311
        elif target_type == 'tree':
4519
5312
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4520
5313
        elif target_type == 'checkout':
4521
 
            reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4522
 
                                                                  bind_to)
 
5314
            reconfiguration = reconfigure.Reconfigure.to_checkout(
 
5315
                directory, bind_to)
4523
5316
        elif target_type == 'lightweight-checkout':
4524
5317
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4525
5318
                directory, bind_to)
4527
5320
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4528
5321
        elif target_type == 'standalone':
4529
5322
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
 
5323
        elif target_type == 'with-trees':
 
5324
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5325
                directory, True)
 
5326
        elif target_type == 'with-no-trees':
 
5327
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5328
                directory, False)
4530
5329
        reconfiguration.apply(force)
4531
5330
 
4532
5331
 
4533
5332
class cmd_switch(Command):
4534
5333
    """Set the branch of a checkout and update.
4535
 
    
 
5334
 
4536
5335
    For lightweight checkouts, this changes the branch being referenced.
4537
5336
    For heavyweight checkouts, this checks that there are no local commits
4538
5337
    versus the current bound branch, then it makes the local branch a mirror
4539
5338
    of the new location and binds to it.
4540
 
    
 
5339
 
4541
5340
    In both cases, the working tree is updated and uncommitted changes
4542
5341
    are merged. The user can commit or revert these as they desire.
4543
5342
 
4547
5346
    directory of the current branch. For example, if you are currently in a
4548
5347
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4549
5348
    /path/to/newbranch.
 
5349
 
 
5350
    Bound branches use the nickname of its master branch unless it is set
 
5351
    locally, in which case switching will update the the local nickname to be
 
5352
    that of the master.
4550
5353
    """
4551
5354
 
4552
5355
    takes_args = ['to_location']
4553
5356
    takes_options = [Option('force',
4554
 
                        help='Switch even if local commits will be lost.')
 
5357
                        help='Switch even if local commits will be lost.'),
 
5358
                     Option('create-branch', short_name='b',
 
5359
                        help='Create the target branch from this one before'
 
5360
                             ' switching to it.'),
4555
5361
                     ]
4556
5362
 
4557
 
    def run(self, to_location, force=False):
 
5363
    def run(self, to_location, force=False, create_branch=False):
4558
5364
        from bzrlib import switch
4559
5365
        tree_location = '.'
4560
5366
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
4561
5367
        try:
4562
 
            to_branch = Branch.open(to_location)
 
5368
            branch = control_dir.open_branch()
 
5369
            had_explicit_nick = branch.get_config().has_explicit_nickname()
4563
5370
        except errors.NotBranchError:
4564
 
            to_branch = Branch.open(
4565
 
                control_dir.open_branch().base + '../' + to_location)
 
5371
            branch = None
 
5372
            had_explicit_nick = False
 
5373
        if create_branch:
 
5374
            if branch is None:
 
5375
                raise errors.BzrCommandError('cannot create branch without'
 
5376
                                             ' source branch')
 
5377
            if '/' not in to_location and '\\' not in to_location:
 
5378
                # This path is meant to be relative to the existing branch
 
5379
                this_url = self._get_branch_location(control_dir)
 
5380
                to_location = urlutils.join(this_url, '..', to_location)
 
5381
            to_branch = branch.bzrdir.sprout(to_location,
 
5382
                                 possible_transports=[branch.bzrdir.root_transport],
 
5383
                                 source_branch=branch).open_branch()
 
5384
            # try:
 
5385
            #     from_branch = control_dir.open_branch()
 
5386
            # except errors.NotBranchError:
 
5387
            #     raise BzrCommandError('Cannot create a branch from this'
 
5388
            #         ' location when we cannot open this branch')
 
5389
            # from_branch.bzrdir.sprout(
 
5390
            pass
 
5391
        else:
 
5392
            try:
 
5393
                to_branch = Branch.open(to_location)
 
5394
            except errors.NotBranchError:
 
5395
                this_url = self._get_branch_location(control_dir)
 
5396
                to_branch = Branch.open(
 
5397
                    urlutils.join(this_url, '..', to_location))
4566
5398
        switch.switch(control_dir, to_branch, force)
 
5399
        if had_explicit_nick:
 
5400
            branch = control_dir.open_branch() #get the new branch!
 
5401
            branch.nick = to_branch.nick
4567
5402
        note('Switched to branch: %s',
4568
5403
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4569
5404
 
 
5405
    def _get_branch_location(self, control_dir):
 
5406
        """Return location of branch for this control dir."""
 
5407
        try:
 
5408
            this_branch = control_dir.open_branch()
 
5409
            # This may be a heavy checkout, where we want the master branch
 
5410
            master_location = this_branch.get_bound_location()
 
5411
            if master_location is not None:
 
5412
                return master_location
 
5413
            # If not, use a local sibling
 
5414
            return this_branch.base
 
5415
        except errors.NotBranchError:
 
5416
            format = control_dir.find_branch_format()
 
5417
            if getattr(format, 'get_reference', None) is not None:
 
5418
                return format.get_reference(control_dir)
 
5419
            else:
 
5420
                return control_dir.root_transport.base
 
5421
 
 
5422
 
 
5423
class cmd_view(Command):
 
5424
    """Manage filtered views.
 
5425
 
 
5426
    Views provide a mask over the tree so that users can focus on
 
5427
    a subset of a tree when doing their work. After creating a view,
 
5428
    commands that support a list of files - status, diff, commit, etc -
 
5429
    effectively have that list of files implicitly given each time.
 
5430
    An explicit list of files can still be given but those files
 
5431
    must be within the current view.
 
5432
 
 
5433
    In most cases, a view has a short life-span: it is created to make
 
5434
    a selected change and is deleted once that change is committed.
 
5435
    At other times, you may wish to create one or more named views
 
5436
    and switch between them.
 
5437
 
 
5438
    To disable the current view without deleting it, you can switch to
 
5439
    the pseudo view called ``off``. This can be useful when you need
 
5440
    to see the whole tree for an operation or two (e.g. merge) but
 
5441
    want to switch back to your view after that.
 
5442
 
 
5443
    :Examples:
 
5444
      To define the current view::
 
5445
 
 
5446
        bzr view file1 dir1 ...
 
5447
 
 
5448
      To list the current view::
 
5449
 
 
5450
        bzr view
 
5451
 
 
5452
      To delete the current view::
 
5453
 
 
5454
        bzr view --delete
 
5455
 
 
5456
      To disable the current view without deleting it::
 
5457
 
 
5458
        bzr view --switch off
 
5459
 
 
5460
      To define a named view and switch to it::
 
5461
 
 
5462
        bzr view --name view-name file1 dir1 ...
 
5463
 
 
5464
      To list a named view::
 
5465
 
 
5466
        bzr view --name view-name
 
5467
 
 
5468
      To delete a named view::
 
5469
 
 
5470
        bzr view --name view-name --delete
 
5471
 
 
5472
      To switch to a named view::
 
5473
 
 
5474
        bzr view --switch view-name
 
5475
 
 
5476
      To list all views defined::
 
5477
 
 
5478
        bzr view --all
 
5479
 
 
5480
      To delete all views::
 
5481
 
 
5482
        bzr view --delete --all
 
5483
    """
 
5484
 
 
5485
    _see_also = []
 
5486
    takes_args = ['file*']
 
5487
    takes_options = [
 
5488
        Option('all',
 
5489
            help='Apply list or delete action to all views.',
 
5490
            ),
 
5491
        Option('delete',
 
5492
            help='Delete the view.',
 
5493
            ),
 
5494
        Option('name',
 
5495
            help='Name of the view to define, list or delete.',
 
5496
            type=unicode,
 
5497
            ),
 
5498
        Option('switch',
 
5499
            help='Name of the view to switch to.',
 
5500
            type=unicode,
 
5501
            ),
 
5502
        ]
 
5503
 
 
5504
    def run(self, file_list,
 
5505
            all=False,
 
5506
            delete=False,
 
5507
            name=None,
 
5508
            switch=None,
 
5509
            ):
 
5510
        tree, file_list = tree_files(file_list, apply_view=False)
 
5511
        current_view, view_dict = tree.views.get_view_info()
 
5512
        if name is None:
 
5513
            name = current_view
 
5514
        if delete:
 
5515
            if file_list:
 
5516
                raise errors.BzrCommandError(
 
5517
                    "Both --delete and a file list specified")
 
5518
            elif switch:
 
5519
                raise errors.BzrCommandError(
 
5520
                    "Both --delete and --switch specified")
 
5521
            elif all:
 
5522
                tree.views.set_view_info(None, {})
 
5523
                self.outf.write("Deleted all views.\n")
 
5524
            elif name is None:
 
5525
                raise errors.BzrCommandError("No current view to delete")
 
5526
            else:
 
5527
                tree.views.delete_view(name)
 
5528
                self.outf.write("Deleted '%s' view.\n" % name)
 
5529
        elif switch:
 
5530
            if file_list:
 
5531
                raise errors.BzrCommandError(
 
5532
                    "Both --switch and a file list specified")
 
5533
            elif all:
 
5534
                raise errors.BzrCommandError(
 
5535
                    "Both --switch and --all specified")
 
5536
            elif switch == 'off':
 
5537
                if current_view is None:
 
5538
                    raise errors.BzrCommandError("No current view to disable")
 
5539
                tree.views.set_view_info(None, view_dict)
 
5540
                self.outf.write("Disabled '%s' view.\n" % (current_view))
 
5541
            else:
 
5542
                tree.views.set_view_info(switch, view_dict)
 
5543
                view_str = views.view_display_str(tree.views.lookup_view())
 
5544
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
 
5545
        elif all:
 
5546
            if view_dict:
 
5547
                self.outf.write('Views defined:\n')
 
5548
                for view in sorted(view_dict):
 
5549
                    if view == current_view:
 
5550
                        active = "=>"
 
5551
                    else:
 
5552
                        active = "  "
 
5553
                    view_str = views.view_display_str(view_dict[view])
 
5554
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
 
5555
            else:
 
5556
                self.outf.write('No views defined.\n')
 
5557
        elif file_list:
 
5558
            if name is None:
 
5559
                # No name given and no current view set
 
5560
                name = 'my'
 
5561
            elif name == 'off':
 
5562
                raise errors.BzrCommandError(
 
5563
                    "Cannot change the 'off' pseudo view")
 
5564
            tree.views.set_view(name, sorted(file_list))
 
5565
            view_str = views.view_display_str(tree.views.lookup_view())
 
5566
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
 
5567
        else:
 
5568
            # list the files
 
5569
            if name is None:
 
5570
                # No name given and no current view set
 
5571
                self.outf.write('No current view.\n')
 
5572
            else:
 
5573
                view_str = views.view_display_str(tree.views.lookup_view(name))
 
5574
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
 
5575
 
4570
5576
 
4571
5577
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):
 
5578
    """Show hooks."""
 
5579
 
 
5580
    hidden = True
 
5581
 
 
5582
    def run(self):
 
5583
        for hook_key in sorted(hooks.known_hooks.keys()):
 
5584
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
 
5585
            self.outf.write("%s:\n" % type(some_hooks).__name__)
 
5586
            for hook_name, hook_point in sorted(some_hooks.items()):
 
5587
                self.outf.write("  %s:\n" % (hook_name,))
 
5588
                found_hooks = list(hook_point)
 
5589
                if found_hooks:
 
5590
                    for hook in found_hooks:
 
5591
                        self.outf.write("    %s\n" %
 
5592
                                        (some_hooks.get_hook_name(hook),))
 
5593
                else:
 
5594
                    self.outf.write("    <no hooks installed>\n")
 
5595
 
 
5596
 
 
5597
class cmd_shelve(Command):
 
5598
    """Temporarily set aside some changes from the current tree.
 
5599
 
 
5600
    Shelve allows you to temporarily put changes you've made "on the shelf",
 
5601
    ie. out of the way, until a later time when you can bring them back from
 
5602
    the shelf with the 'unshelve' command.  The changes are stored alongside
 
5603
    your working tree, and so they aren't propagated along with your branch nor
 
5604
    will they survive its deletion.
 
5605
 
 
5606
    If shelve --list is specified, previously-shelved changes are listed.
 
5607
 
 
5608
    Shelve is intended to help separate several sets of changes that have
 
5609
    been inappropriately mingled.  If you just want to get rid of all changes
 
5610
    and you don't need to restore them later, use revert.  If you want to
 
5611
    shelve all text changes at once, use shelve --all.
 
5612
 
 
5613
    If filenames are specified, only the changes to those files will be
 
5614
    shelved. Other files will be left untouched.
 
5615
 
 
5616
    If a revision is specified, changes since that revision will be shelved.
 
5617
 
 
5618
    You can put multiple items on the shelf, and by default, 'unshelve' will
 
5619
    restore the most recently shelved changes.
 
5620
    """
 
5621
 
 
5622
    takes_args = ['file*']
 
5623
 
 
5624
    takes_options = [
 
5625
        'revision',
 
5626
        Option('all', help='Shelve all changes.'),
 
5627
        'message',
 
5628
        RegistryOption('writer', 'Method to use for writing diffs.',
 
5629
                       bzrlib.option.diff_writer_registry,
 
5630
                       value_switches=True, enum_switch=False),
 
5631
 
 
5632
        Option('list', help='List shelved changes.'),
 
5633
        Option('destroy',
 
5634
               help='Destroy removed changes instead of shelving them.'),
 
5635
    ]
 
5636
    _see_also = ['unshelve']
 
5637
 
 
5638
    def run(self, revision=None, all=False, file_list=None, message=None,
 
5639
            writer=None, list=False, destroy=False):
 
5640
        if list:
 
5641
            return self.run_for_list()
 
5642
        from bzrlib.shelf_ui import Shelver
 
5643
        if writer is None:
 
5644
            writer = bzrlib.option.diff_writer_registry.get()
 
5645
        try:
 
5646
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
 
5647
                file_list, message, destroy=destroy)
 
5648
            try:
 
5649
                shelver.run()
 
5650
            finally:
 
5651
                shelver.work_tree.unlock()
 
5652
        except errors.UserAbort:
 
5653
            return 0
 
5654
 
 
5655
    def run_for_list(self):
 
5656
        tree = WorkingTree.open_containing('.')[0]
 
5657
        tree.lock_read()
 
5658
        try:
 
5659
            manager = tree.get_shelf_manager()
 
5660
            shelves = manager.active_shelves()
 
5661
            if len(shelves) == 0:
 
5662
                note('No shelved changes.')
 
5663
                return 0
 
5664
            for shelf_id in reversed(shelves):
 
5665
                message = manager.get_metadata(shelf_id).get('message')
 
5666
                if message is None:
 
5667
                    message = '<no message>'
 
5668
                self.outf.write('%3d: %s\n' % (shelf_id, message))
 
5669
            return 1
 
5670
        finally:
 
5671
            tree.unlock()
 
5672
 
 
5673
 
 
5674
class cmd_unshelve(Command):
 
5675
    """Restore shelved changes.
 
5676
 
 
5677
    By default, the most recently shelved changes are restored. However if you
 
5678
    specify a shelf by id those changes will be restored instead.  This works
 
5679
    best when the changes don't depend on each other.
 
5680
    """
 
5681
 
 
5682
    takes_args = ['shelf_id?']
 
5683
    takes_options = [
 
5684
        RegistryOption.from_kwargs(
 
5685
            'action', help="The action to perform.",
 
5686
            enum_switch=False, value_switches=True,
 
5687
            apply="Apply changes and remove from the shelf.",
 
5688
            dry_run="Show changes, but do not apply or remove them.",
 
5689
            delete_only="Delete changes without applying them."
 
5690
        )
 
5691
    ]
 
5692
    _see_also = ['shelve']
 
5693
 
 
5694
    def run(self, shelf_id=None, action='apply'):
 
5695
        from bzrlib.shelf_ui import Unshelver
 
5696
        unshelver = Unshelver.from_args(shelf_id, action)
 
5697
        try:
 
5698
            unshelver.run()
 
5699
        finally:
 
5700
            unshelver.tree.unlock()
 
5701
 
 
5702
 
 
5703
class cmd_clean_tree(Command):
 
5704
    """Remove unwanted files from working tree.
 
5705
 
 
5706
    By default, only unknown files, not ignored files, are deleted.  Versioned
 
5707
    files are never deleted.
 
5708
 
 
5709
    Another class is 'detritus', which includes files emitted by bzr during
 
5710
    normal operations and selftests.  (The value of these files decreases with
 
5711
    time.)
 
5712
 
 
5713
    If no options are specified, unknown files are deleted.  Otherwise, option
 
5714
    flags are respected, and may be combined.
 
5715
 
 
5716
    To check what clean-tree will do, use --dry-run.
 
5717
    """
 
5718
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5719
                     Option('detritus', help='Delete conflict files, merge'
 
5720
                            ' backups, and failed selftest dirs.'),
 
5721
                     Option('unknown',
 
5722
                            help='Delete files unknown to bzr (default).'),
 
5723
                     Option('dry-run', help='Show files to delete instead of'
 
5724
                            ' deleting them.'),
 
5725
                     Option('force', help='Do not prompt before deleting.')]
 
5726
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
 
5727
            force=False):
 
5728
        from bzrlib.clean_tree import clean_tree
 
5729
        if not (unknown or ignored or detritus):
 
5730
            unknown = True
 
5731
        if dry_run:
 
5732
            force = True
 
5733
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5734
                   dry_run=dry_run, no_prompt=force)
 
5735
 
 
5736
 
 
5737
class cmd_reference(Command):
 
5738
    """list, view and set branch locations for nested trees.
 
5739
 
 
5740
    If no arguments are provided, lists the branch locations for nested trees.
 
5741
    If one argument is provided, display the branch location for that tree.
 
5742
    If two arguments are provided, set the branch location for that tree.
 
5743
    """
 
5744
 
 
5745
    hidden = True
 
5746
 
 
5747
    takes_args = ['path?', 'location?']
 
5748
 
 
5749
    def run(self, path=None, location=None):
 
5750
        branchdir = '.'
 
5751
        if path is not None:
 
5752
            branchdir = path
 
5753
        tree, branch, relpath =(
 
5754
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
 
5755
        if path is not None:
 
5756
            path = relpath
 
5757
        if tree is None:
 
5758
            tree = branch.basis_tree()
4579
5759
        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),))
 
5760
            info = branch._get_all_reference_info().iteritems()
 
5761
            self._display_reference_info(tree, branch, info)
 
5762
        else:
 
5763
            file_id = tree.path2id(path)
 
5764
            if file_id is None:
 
5765
                raise errors.NotVersionedError(path)
 
5766
            if location is None:
 
5767
                info = [(file_id, branch.get_reference_info(file_id))]
 
5768
                self._display_reference_info(tree, branch, info)
4589
5769
            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()
 
5770
                branch.set_reference_info(file_id, path, location)
 
5771
 
 
5772
    def _display_reference_info(self, tree, branch, info):
 
5773
        ref_list = []
 
5774
        for file_id, (path, location) in info:
 
5775
            try:
 
5776
                path = tree.id2path(file_id)
 
5777
            except errors.NoSuchId:
 
5778
                pass
 
5779
            ref_list.append((path, location))
 
5780
        for path, location in sorted(ref_list):
 
5781
            self.outf.write('%s %s\n' % (path, location))
4613
5782
 
4614
5783
 
4615
5784
# these get imported and then picked up by the scan for cmd_*
4616
5785
# 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 
 
5786
# we do need to load at least some information about them to know of
4618
5787
# aliases.  ideally we would avoid loading the implementation until the
4619
5788
# details were needed.
4620
5789
from bzrlib.cmd_version_info import cmd_version_info
4622
5791
from bzrlib.bundle.commands import (
4623
5792
    cmd_bundle_info,
4624
5793
    )
 
5794
from bzrlib.foreign import cmd_dpush
4625
5795
from bzrlib.sign_my_commits import cmd_sign_my_commits
4626
5796
from bzrlib.weave_commands import cmd_versionedfile_list, \
4627
5797
        cmd_weave_plan_merge, cmd_weave_merge_text