~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Naoki INADA
  • Date: 2009-10-29 10:01:19 UTC
  • mto: (4634.97.3 2.0)
  • mto: This revision was merged to the branch mainline in revision 4798.
  • Revision ID: inada-n@klab.jp-20091029100119-uckv9t7ej2qrghw3
import doc-ja rev90

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007 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]
 
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):
 
181
    """Convert file_list into a list of relpaths in tree.
 
182
 
 
183
    :param tree: A tree to operate on.
 
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
 
187
    :return: A list of relative paths.
 
188
    :raises errors.PathNotChild: When a provided path is in a different tree
 
189
        than tree.
 
190
    """
 
191
    if file_list is None:
 
192
        return None
 
193
    if tree.supports_views() and apply_view:
 
194
        view_files = tree.views.lookup_view()
 
195
    else:
 
196
        view_files = []
90
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
91
204
    for filename in file_list:
92
205
        try:
93
 
            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)
94
210
        except errors.PathNotChild:
95
211
            raise errors.FileInWrongBranch(tree.branch, filename)
96
 
    return tree, new_list
97
 
 
98
 
 
99
 
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
100
 
def get_format_type(typestring):
101
 
    """Parse and return a format specifier."""
102
 
    # Have to use BzrDirMetaFormat1 directly, so that
103
 
    # RepositoryFormat.set_default_format works
104
 
    if typestring == "default":
105
 
        return bzrdir.BzrDirMetaFormat1()
 
212
    return new_list
 
213
 
 
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
106
218
    try:
107
 
        return bzrdir.format_registry.make_bzrdir(typestring)
108
 
    except KeyError:
109
 
        msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
110
 
        raise errors.BzrCommandError(msg)
 
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
111
225
 
112
226
 
113
227
# TODO: Make sure no commands unconditionally use the working directory as a
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
 
    use bzr -SV.
 
265
    use bzr status -SV.
152
266
 
153
267
    If no arguments are specified, the status of the entire working
154
268
    directory is shown.  Otherwise, only the status of the specified
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.',
169
 
                            short_name='V')
 
288
                            short_name='V'),
 
289
                     Option('no-pending', help='Don\'t show pending merges.',
 
290
                           ),
170
291
                     ]
171
292
    aliases = ['st', 'stat']
172
293
 
173
294
    encoding_type = 'replace'
174
295
    _see_also = ['diff', 'revert', 'status-flags']
175
 
    
 
296
 
176
297
    @display_command
177
298
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
178
 
            versioned=False):
 
299
            versioned=False, no_pending=False, verbose=False):
179
300
        from bzrlib.status import show_tree_status
180
301
 
181
302
        if revision and len(revision) > 2:
182
303
            raise errors.BzrCommandError('bzr status --revision takes exactly'
183
304
                                         ' one or two revision specifiers')
184
305
 
185
 
        tree, file_list = tree_files(file_list)
186
 
            
 
306
        tree, relfile_list = tree_files(file_list)
 
307
        # Avoid asking for specific files when that is not needed.
 
308
        if relfile_list == ['']:
 
309
            relfile_list = None
 
310
            # Don't disable pending merges for full trees other than '.'.
 
311
            if file_list == ['.']:
 
312
                no_pending = True
 
313
        # A specific path within a tree was given.
 
314
        elif relfile_list is not None:
 
315
            no_pending = True
187
316
        show_tree_status(tree, show_ids=show_ids,
188
 
                         specific_files=file_list, revision=revision,
189
 
                         to_file=self.outf, short=short, versioned=versioned)
 
317
                         specific_files=relfile_list, revision=revision,
 
318
                         to_file=self.outf, short=short, versioned=versioned,
 
319
                         show_pending=(not no_pending), verbose=verbose)
190
320
 
191
321
 
192
322
class cmd_cat_revision(Command):
193
323
    """Write out metadata for a revision.
194
 
    
 
324
 
195
325
    The revision to print can either be specified by a specific
196
326
    revision identifier, or you can use --revision.
197
327
    """
201
331
    takes_options = ['revision']
202
332
    # cat-revision is more for frontends so should be exact
203
333
    encoding = 'strict'
204
 
    
 
334
 
205
335
    @display_command
206
336
    def run(self, revision_id=None, revision=None):
207
337
        if revision_id is not None and revision is not None:
215
345
        # TODO: jam 20060112 should cat-revision always output utf-8?
216
346
        if revision_id is not None:
217
347
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
218
 
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
348
            try:
 
349
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
350
            except errors.NoSuchRevision:
 
351
                msg = "The repository %s contains no revision %s." % (b.repository.base,
 
352
                    revision_id)
 
353
                raise errors.BzrCommandError(msg)
219
354
        elif revision is not None:
220
355
            for rev in revision:
221
356
                if rev is None:
222
357
                    raise errors.BzrCommandError('You cannot specify a NULL'
223
358
                                                 ' revision.')
224
 
                revno, rev_id = rev.in_history(b)
 
359
                rev_id = rev.as_revision_id(b)
225
360
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
226
 
    
 
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
 
227
436
 
228
437
class cmd_remove_tree(Command):
229
438
    """Remove the working tree from a given branch/checkout.
234
443
    To re-create the working tree, use "bzr checkout".
235
444
    """
236
445
    _see_also = ['checkout', 'working-trees']
237
 
 
238
446
    takes_args = ['location?']
 
447
    takes_options = [
 
448
        Option('force',
 
449
               help='Remove the working tree even if it has '
 
450
                    'uncommitted changes.'),
 
451
        ]
239
452
 
240
 
    def run(self, location='.'):
 
453
    def run(self, location='.', force=False):
241
454
        d = bzrdir.BzrDir.open(location)
242
 
        
 
455
 
243
456
        try:
244
457
            working = d.open_workingtree()
245
458
        except errors.NoWorkingTree:
246
459
            raise errors.BzrCommandError("No working tree to remove")
247
460
        except errors.NotLocalUrl:
248
 
            raise errors.BzrCommandError("You cannot remove the working tree of a "
249
 
                                         "remote path")
250
 
        
 
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
 
251
468
        working_path = working.bzrdir.root_transport.base
252
469
        branch_path = working.branch.bzrdir.root_transport.base
253
470
        if working_path != branch_path:
254
 
            raise errors.BzrCommandError("You cannot remove the working tree from "
255
 
                                         "a lightweight checkout")
256
 
        
 
471
            raise errors.BzrCommandError("You cannot remove the working tree"
 
472
                                         " from a lightweight checkout")
 
473
 
257
474
        d.destroy_workingtree()
258
 
        
 
475
 
259
476
 
260
477
class cmd_revno(Command):
261
478
    """Show current revision number.
265
482
 
266
483
    _see_also = ['info']
267
484
    takes_args = ['location?']
 
485
    takes_options = [
 
486
        Option('tree', help='Show revno of working tree'),
 
487
        ]
268
488
 
269
489
    @display_command
270
 
    def run(self, location=u'.'):
271
 
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
272
 
        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')
273
515
 
274
516
 
275
517
class cmd_revision_info(Command):
277
519
    """
278
520
    hidden = True
279
521
    takes_args = ['revision_info*']
280
 
    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
        ]
281
532
 
282
533
    @display_command
283
 
    def run(self, revision=None, revision_info_list=[]):
284
 
 
285
 
        revs = []
286
 
        if revision is not None:
287
 
            revs.extend(revision)
288
 
        if revision_info_list is not None:
289
 
            for rev in revision_info_list:
290
 
                revs.append(RevisionSpec.from_string(rev))
291
 
 
292
 
        b = Branch.open_containing(u'.')[0]
293
 
 
294
 
        if len(revs) == 0:
295
 
            revs.append(RevisionSpec.from_string('-1'))
296
 
 
297
 
        for rev in revs:
298
 
            revinfo = rev.in_history(b)
299
 
            if revinfo.revno is None:
300
 
                dotted_map = b.get_revision_id_to_revno_map()
301
 
                revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
302
 
                print '%s %s' % (revno, revinfo.rev_id)
 
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()
303
575
            else:
304
 
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
305
 
 
306
 
    
 
576
                wt.unlock()
 
577
 
 
578
        for ri in revinfos:
 
579
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
 
580
 
 
581
 
307
582
class cmd_add(Command):
308
583
    """Add specified files or directories.
309
584
 
327
602
    you should never need to explicitly add a directory, they'll just
328
603
    get added when you add a file in the directory.
329
604
 
330
 
    --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
331
606
    add them.
332
607
 
333
608
    --file-ids-from will try to use the file ids from the supplied path.
337
612
    branches that will be merged later (without showing the two different
338
613
    adds as a conflict). It is also useful when merging another project
339
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.
340
618
    """
341
619
    takes_args = ['file*']
342
620
    takes_options = [
350
628
               help='Lookup file ids from this tree.'),
351
629
        ]
352
630
    encoding_type = 'replace'
353
 
    _see_also = ['remove']
 
631
    _see_also = ['remove', 'ignore']
354
632
 
355
633
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
356
634
            file_ids_from=None):
376
654
            base_tree.lock_read()
377
655
        try:
378
656
            file_list = self._maybe_expand_globs(file_list)
379
 
            if file_list:
380
 
                tree = WorkingTree.open_containing(file_list[0])[0]
381
 
            else:
382
 
                tree = WorkingTree.open_containing(u'.')[0]
 
657
            tree, file_list = tree_files_for_add(file_list)
383
658
            added, ignored = tree.smart_add(file_list, not
384
659
                no_recurse, action=action, save=not dry_run)
385
660
        finally:
389
664
            if verbose:
390
665
                for glob in sorted(ignored.keys()):
391
666
                    for path in ignored[glob]:
392
 
                        self.outf.write("ignored %s matching \"%s\"\n" 
 
667
                        self.outf.write("ignored %s matching \"%s\"\n"
393
668
                                        % (path, glob))
394
 
            else:
395
 
                match_len = 0
396
 
                for glob, paths in ignored.items():
397
 
                    match_len += len(paths)
398
 
                self.outf.write("ignored %d file(s).\n" % match_len)
399
 
            self.outf.write("If you wish to add some of these files,"
400
 
                            " please add them by name.\n")
401
669
 
402
670
 
403
671
class cmd_mkdir(Command):
422
690
 
423
691
    takes_args = ['filename']
424
692
    hidden = True
425
 
    
 
693
 
426
694
    @display_command
427
695
    def run(self, filename):
428
696
        # TODO: jam 20050106 Can relpath return a munged path if
458
726
        if kind and kind not in ['file', 'directory', 'symlink']:
459
727
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
460
728
 
 
729
        revision = _get_one_revision('inventory', revision)
461
730
        work_tree, file_list = tree_files(file_list)
462
731
        work_tree.lock_read()
463
732
        try:
464
733
            if revision is not None:
465
 
                if len(revision) > 1:
466
 
                    raise errors.BzrCommandError(
467
 
                        'bzr inventory --revision takes exactly one revision'
468
 
                        ' identifier')
469
 
                revision_id = revision[0].in_history(work_tree.branch).rev_id
470
 
                tree = work_tree.branch.repository.revision_tree(revision_id)
 
734
                tree = revision.as_tree(work_tree.branch)
471
735
 
472
736
                extra_trees = [work_tree]
473
737
                tree.lock_read()
523
787
    takes_args = ['names*']
524
788
    takes_options = [Option("after", help="Move only the bzr identifier"
525
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.'),
526
792
        ]
527
793
    aliases = ['move', 'rename']
528
794
    encoding_type = 'replace'
529
795
 
530
 
    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.')
531
801
        if names_list is None:
532
802
            names_list = []
533
 
 
534
803
        if len(names_list) < 2:
535
804
            raise errors.BzrCommandError("missing file argument")
536
 
        tree, rel_names = tree_files(names_list)
537
 
        
538
 
        if os.path.isdir(names_list[-1]):
 
805
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
806
        tree.lock_tree_write()
 
807
        try:
 
808
            self._run(tree, names_list, rel_names, after)
 
809
        finally:
 
810
            tree.unlock()
 
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
 
 
826
    def _run(self, tree, names_list, rel_names, after):
 
827
        into_existing = osutils.isdir(names_list[-1])
 
828
        if into_existing and len(names_list) == 2:
 
829
            # special cases:
 
830
            # a. case-insensitive filesystem and change case of dir
 
831
            # b. move directory after the fact (if the source used to be
 
832
            #    a directory, but now doesn't exist in the working tree
 
833
            #    and the target is an existing directory, just rename it)
 
834
            if (not tree.case_sensitive
 
835
                and rel_names[0].lower() == rel_names[1].lower()):
 
836
                into_existing = False
 
837
            else:
 
838
                inv = tree.inventory
 
839
                # 'fix' the case of a potential 'from'
 
840
                from_id = tree.path2id(
 
841
                            tree.get_canonical_inventory_path(rel_names[0]))
 
842
                if (not osutils.lexists(names_list[0]) and
 
843
                    from_id and inv.get_file_kind(from_id) == "directory"):
 
844
                    into_existing = False
 
845
        # move/rename
 
846
        if into_existing:
539
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)
540
851
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
541
852
                self.outf.write("%s => %s\n" % pair)
542
853
        else:
544
855
                raise errors.BzrCommandError('to mv multiple files the'
545
856
                                             ' destination must be a versioned'
546
857
                                             ' directory')
547
 
            tree.rename_one(rel_names[0], rel_names[1], after=after)
548
 
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
549
 
            
550
 
    
 
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))
 
903
 
 
904
 
551
905
class cmd_pull(Command):
552
906
    """Turn this branch into a mirror of another branch.
553
907
 
566
920
    that, you can omit the location to use the default.  To change the
567
921
    default, use --remember. The value will only be saved if the remote
568
922
    location can be accessed.
 
923
 
 
924
    Note: The location can be specified either in the form of a branch,
 
925
    or in the form of a path to a file containing a merge directive generated
 
926
    with bzr send.
569
927
    """
570
928
 
571
 
    _see_also = ['push', 'update', 'status-flags']
 
929
    _see_also = ['push', 'update', 'status-flags', 'send']
572
930
    takes_options = ['remember', 'overwrite', 'revision',
573
931
        custom_help('verbose',
574
932
            help='Show logs of pulled revisions.'),
578
936
            short_name='d',
579
937
            type=unicode,
580
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
            ),
581
944
        ]
582
945
    takes_args = ['location?']
583
946
    encoding_type = 'replace'
584
947
 
585
948
    def run(self, location=None, remember=False, overwrite=False,
586
949
            revision=None, verbose=False,
587
 
            directory=None):
 
950
            directory=None, local=False):
588
951
        # FIXME: too much stuff is in the command class
589
952
        revision_id = None
590
953
        mergeable = None
596
959
        except errors.NoWorkingTree:
597
960
            tree_to = None
598
961
            branch_to = Branch.open_containing(directory)[0]
 
962
        
 
963
        if local and not branch_to.get_bound_location():
 
964
            raise errors.LocalRequiresBoundBranch()
599
965
 
600
966
        possible_transports = []
601
967
        if location is not None:
602
 
            mergeable, location_transport = _get_mergeable_helper(location)
603
 
            possible_transports.append(location_transport)
 
968
            try:
 
969
                mergeable = bundle.read_mergeable_from_url(location,
 
970
                    possible_transports=possible_transports)
 
971
            except errors.NotABundle:
 
972
                mergeable = None
604
973
 
605
974
        stored_loc = branch_to.get_parent()
606
975
        if location is None:
610
979
            else:
611
980
                display_url = urlutils.unescape_for_display(stored_loc,
612
981
                        self.outf.encoding)
613
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
982
                if not is_quiet():
 
983
                    self.outf.write("Using saved parent location: %s\n" % display_url)
614
984
                location = stored_loc
615
 
                location_transport = transport.get_transport(
616
 
                    location, possible_transports=possible_transports)
617
985
 
 
986
        revision = _get_one_revision('pull', revision)
618
987
        if mergeable is not None:
619
988
            if revision is not None:
620
989
                raise errors.BzrCommandError(
624
993
                mergeable.get_merge_request(branch_to.repository)
625
994
            branch_from = branch_to
626
995
        else:
627
 
            branch_from = Branch.open_from_transport(location_transport)
 
996
            branch_from = Branch.open(location,
 
997
                possible_transports=possible_transports)
628
998
 
629
999
            if branch_to.get_parent() is None or remember:
630
1000
                branch_to.set_parent(branch_from.base)
631
1001
 
632
 
        if revision is not None:
633
 
            if len(revision) == 1:
634
 
                revision_id = revision[0].in_history(branch_from).rev_id
635
 
            else:
636
 
                raise errors.BzrCommandError(
637
 
                    'bzr pull --revision takes one value.')
638
 
 
639
 
        if verbose:
640
 
            old_rh = branch_to.revision_history()
641
 
        if tree_to is not None:
642
 
            change_reporter = delta._ChangeReporter(
643
 
                unversioned_filter=tree_to.is_ignored)
644
 
            result = tree_to.pull(branch_from, overwrite, revision_id,
645
 
                                  change_reporter,
646
 
                                  possible_transports=possible_transports)
647
 
        else:
648
 
            result = branch_to.pull(branch_from, overwrite, revision_id)
649
 
 
650
 
        result.report(self.outf)
651
 
        if verbose:
652
 
            new_rh = branch_to.revision_history()
653
 
            log.show_changed_revisions(branch_to, old_rh, new_rh,
654
 
                                       to_file=self.outf)
 
1002
        if branch_from is not branch_to:
 
1003
            branch_from.lock_read()
 
1004
        try:
 
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()
 
1029
        finally:
 
1030
            if branch_from is not branch_to:
 
1031
                branch_from.unlock()
655
1032
 
656
1033
 
657
1034
class cmd_push(Command):
658
1035
    """Update a mirror of this branch.
659
 
    
 
1036
 
660
1037
    The target branch will not have its working tree populated because this
661
1038
    is both expensive, and is not supported on remote file systems.
662
 
    
 
1039
 
663
1040
    Some smart servers or protocols *may* put the working tree in place in
664
1041
    the future.
665
1042
 
669
1046
 
670
1047
    If branches have diverged, you can use 'bzr push --overwrite' to replace
671
1048
    the other branch completely, discarding its unmerged changes.
672
 
    
 
1049
 
673
1050
    If you want to ensure you have the different changes in the other branch,
674
1051
    do a merge (see bzr help merge) from the other branch, and commit that.
675
1052
    After that you will be able to do a push without '--overwrite'.
681
1058
    """
682
1059
 
683
1060
    _see_also = ['pull', 'update', 'working-trees']
684
 
    takes_options = ['remember', 'overwrite', 'verbose',
 
1061
    takes_options = ['remember', 'overwrite', 'verbose', 'revision',
685
1062
        Option('create-prefix',
686
1063
               help='Create the path leading up to the branch '
687
1064
                    'if it does not already exist.'),
696
1073
                    ' directory exists, but does not already'
697
1074
                    ' have a control directory.  This flag will'
698
1075
                    ' allow push to proceed.'),
 
1076
        Option('stacked',
 
1077
            help='Create a stacked branch that references the public location '
 
1078
                'of the parent branch.'),
 
1079
        Option('stacked-on',
 
1080
            help='Create a stacked branch that refers to another branch '
 
1081
                'for the commit history. Only the work not present in the '
 
1082
                'referenced branch is included in the branch created.',
 
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.'),
699
1087
        ]
700
1088
    takes_args = ['location?']
701
1089
    encoding_type = 'replace'
702
1090
 
703
1091
    def run(self, location=None, remember=False, overwrite=False,
704
 
            create_prefix=False, verbose=False,
705
 
            use_existing_dir=False,
706
 
            directory=None):
707
 
        # FIXME: Way too big!  Put this into a function called from the
708
 
        # command.
 
1092
        create_prefix=False, verbose=False, revision=None,
 
1093
        use_existing_dir=False, directory=None, stacked_on=None,
 
1094
        stacked=False, strict=None):
 
1095
        from bzrlib.push import _show_push_branch
 
1096
 
709
1097
        if directory is None:
710
1098
            directory = '.'
711
 
        br_from = Branch.open_containing(directory)[0]
712
 
        stored_loc = br_from.get_push_location()
 
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)
 
1107
        if revision is not None:
 
1108
            revision_id = revision.in_history(br_from).rev_id
 
1109
        else:
 
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.')
 
1122
 
 
1123
        # Get the stacked_on branch, if any
 
1124
        if stacked_on is not None:
 
1125
            stacked_on = urlutils.normalize_url(stacked_on)
 
1126
        elif stacked:
 
1127
            parent_url = br_from.get_parent()
 
1128
            if parent_url:
 
1129
                parent = Branch.open(parent_url)
 
1130
                stacked_on = parent.get_public_branch()
 
1131
                if not stacked_on:
 
1132
                    # I considered excluding non-http url's here, thus forcing
 
1133
                    # 'public' branches only, but that only works for some
 
1134
                    # users, so it's best to just depend on the user spotting an
 
1135
                    # error by the feedback given to them. RBC 20080227.
 
1136
                    stacked_on = parent_url
 
1137
            if not stacked_on:
 
1138
                raise errors.BzrCommandError(
 
1139
                    "Could not determine branch to refer to.")
 
1140
 
 
1141
        # Get the destination location
713
1142
        if location is None:
 
1143
            stored_loc = br_from.get_push_location()
714
1144
            if stored_loc is None:
715
 
                raise errors.BzrCommandError("No push location known or specified.")
 
1145
                raise errors.BzrCommandError(
 
1146
                    "No push location known or specified.")
716
1147
            else:
717
1148
                display_url = urlutils.unescape_for_display(stored_loc,
718
1149
                        self.outf.encoding)
719
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
1150
                self.outf.write("Using saved push location: %s\n" % display_url)
720
1151
                location = stored_loc
721
1152
 
722
 
        to_transport = transport.get_transport(location)
723
 
 
724
 
        br_to = repository_to = dir_to = None
725
 
        try:
726
 
            dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
727
 
        except errors.NotBranchError:
728
 
            pass # Didn't find anything
729
 
        else:
730
 
            # If we can open a branch, use its direct repository, otherwise see
731
 
            # if there is a repository without a branch.
732
 
            try:
733
 
                br_to = dir_to.open_branch()
734
 
            except errors.NotBranchError:
735
 
                # Didn't find a branch, can we find a repository?
736
 
                try:
737
 
                    repository_to = dir_to.find_repository()
738
 
                except errors.NoRepositoryPresent:
739
 
                    pass
740
 
            else:
741
 
                # Found a branch, so we must have found a repository
742
 
                repository_to = br_to.repository
743
 
        push_result = None
744
 
        if verbose:
745
 
            old_rh = []
746
 
        if dir_to is None:
747
 
            # The destination doesn't exist; create it.
748
 
            # XXX: Refactor the create_prefix/no_create_prefix code into a
749
 
            #      common helper function
750
 
            try:
751
 
                to_transport.mkdir('.')
752
 
            except errors.FileExists:
753
 
                if not use_existing_dir:
754
 
                    raise errors.BzrCommandError("Target directory %s"
755
 
                         " already exists, but does not have a valid .bzr"
756
 
                         " directory. Supply --use-existing-dir to push"
757
 
                         " there anyway." % location)
758
 
            except errors.NoSuchFile:
759
 
                if not create_prefix:
760
 
                    raise errors.BzrCommandError("Parent directory of %s"
761
 
                        " does not exist."
762
 
                        "\nYou may supply --create-prefix to create all"
763
 
                        " leading parent directories."
764
 
                        % location)
765
 
                _create_prefix(to_transport)
766
 
 
767
 
            # Now the target directory exists, but doesn't have a .bzr
768
 
            # directory. So we need to create it, along with any work to create
769
 
            # all of the dependent branches, etc.
770
 
            dir_to = br_from.bzrdir.clone_on_transport(to_transport,
771
 
                revision_id=br_from.last_revision())
772
 
            br_to = dir_to.open_branch()
773
 
            # TODO: Some more useful message about what was copied
774
 
            note('Created new branch.')
775
 
            # We successfully created the target, remember it
776
 
            if br_from.get_push_location() is None or remember:
777
 
                br_from.set_push_location(br_to.base)
778
 
        elif repository_to is None:
779
 
            # we have a bzrdir but no branch or repository
780
 
            # XXX: Figure out what to do other than complain.
781
 
            raise errors.BzrCommandError("At %s you have a valid .bzr control"
782
 
                " directory, but not a branch or repository. This is an"
783
 
                " unsupported configuration. Please move the target directory"
784
 
                " out of the way and try again."
785
 
                % location)
786
 
        elif br_to is None:
787
 
            # We have a repository but no branch, copy the revisions, and then
788
 
            # create a branch.
789
 
            last_revision_id = br_from.last_revision()
790
 
            repository_to.fetch(br_from.repository,
791
 
                                revision_id=last_revision_id)
792
 
            br_to = br_from.clone(dir_to, revision_id=last_revision_id)
793
 
            note('Created new branch.')
794
 
            if br_from.get_push_location() is None or remember:
795
 
                br_from.set_push_location(br_to.base)
796
 
        else: # We have a valid to branch
797
 
            # We were able to connect to the remote location, so remember it
798
 
            # we don't need to successfully push because of possible divergence.
799
 
            if br_from.get_push_location() is None or remember:
800
 
                br_from.set_push_location(br_to.base)
801
 
            if verbose:
802
 
                old_rh = br_to.revision_history()
803
 
            try:
804
 
                try:
805
 
                    tree_to = dir_to.open_workingtree()
806
 
                except errors.NotLocalUrl:
807
 
                    warning("This transport does not update the working " 
808
 
                            "tree of: %s. See 'bzr help working-trees' for "
809
 
                            "more information." % br_to.base)
810
 
                    push_result = br_from.push(br_to, overwrite)
811
 
                except errors.NoWorkingTree:
812
 
                    push_result = br_from.push(br_to, overwrite)
813
 
                else:
814
 
                    tree_to.lock_write()
815
 
                    try:
816
 
                        push_result = br_from.push(tree_to.branch, overwrite)
817
 
                        tree_to.update()
818
 
                    finally:
819
 
                        tree_to.unlock()
820
 
            except errors.DivergedBranches:
821
 
                raise errors.BzrCommandError('These branches have diverged.'
822
 
                                        '  Try using "merge" and then "push".')
823
 
        if push_result is not None:
824
 
            push_result.report(self.outf)
825
 
        elif verbose:
826
 
            new_rh = br_to.revision_history()
827
 
            if old_rh != new_rh:
828
 
                # Something changed
829
 
                from bzrlib.log import show_changed_revisions
830
 
                show_changed_revisions(br_to, old_rh, new_rh,
831
 
                                       to_file=self.outf)
832
 
        else:
833
 
            # we probably did a clone rather than a push, so a message was
834
 
            # emitted above
835
 
            pass
 
1153
        _show_push_branch(br_from, revision_id, location, self.outf,
 
1154
            verbose=verbose, overwrite=overwrite, remember=remember,
 
1155
            stacked_on=stacked_on, create_prefix=create_prefix,
 
1156
            use_existing_dir=use_existing_dir)
836
1157
 
837
1158
 
838
1159
class cmd_branch(Command):
839
 
    """Create a new copy of a branch.
 
1160
    """Create a new branch that is a copy of an existing branch.
840
1161
 
841
1162
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
842
1163
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
851
1172
 
852
1173
    _see_also = ['checkout']
853
1174
    takes_args = ['from_location', 'to_location?']
854
 
    takes_options = ['revision']
 
1175
    takes_options = ['revision', Option('hardlink',
 
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."),
 
1182
        Option('stacked',
 
1183
            help='Create a stacked branch referring to the source branch. '
 
1184
                'The new branch will depend on the availability of the source '
 
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.'),
 
1193
        ]
855
1194
    aliases = ['get', 'clone']
856
1195
 
857
 
    def run(self, from_location, to_location=None, revision=None):
 
1196
    def run(self, from_location, to_location=None, revision=None,
 
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
858
1200
        from bzrlib.tag import _merge_tags_if_possible
859
 
        if revision is None:
860
 
            revision = [None]
861
 
        elif len(revision) > 1:
862
 
            raise errors.BzrCommandError(
863
 
                'bzr branch --revision takes exactly 1 revision value')
864
 
 
865
 
        br_from = Branch.open(from_location)
 
1201
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
 
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)
866
1207
        br_from.lock_read()
867
1208
        try:
868
 
            if len(revision) == 1 and revision[0] is not None:
869
 
                revision_id = revision[0].in_history(br_from)[1]
 
1209
            if revision is not None:
 
1210
                revision_id = revision.as_revision_id(br_from)
870
1211
            else:
871
1212
                # FIXME - wt.last_revision, fallback to branch, fall back to
872
1213
                # None or perhaps NULL_REVISION to mean copy nothing
874
1215
                revision_id = br_from.last_revision()
875
1216
            if to_location is None:
876
1217
                to_location = urlutils.derive_to_location(from_location)
877
 
                name = None
878
 
            else:
879
 
                name = os.path.basename(to_location) + '\n'
880
 
 
881
1218
            to_transport = transport.get_transport(to_location)
882
1219
            try:
883
1220
                to_transport.mkdir('.')
884
1221
            except errors.FileExists:
885
 
                raise errors.BzrCommandError('Target directory "%s" already'
886
 
                                             ' 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)
887
1232
            except errors.NoSuchFile:
888
1233
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
889
1234
                                             % to_location)
890
1235
            try:
891
1236
                # preserve whatever source format we have.
892
1237
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
893
 
                                            possible_transports=[to_transport])
 
1238
                                            possible_transports=[to_transport],
 
1239
                                            accelerator_tree=accelerator_tree,
 
1240
                                            hardlink=hardlink, stacked=stacked,
 
1241
                                            force_new_repo=standalone,
 
1242
                                            create_tree_if_local=not no_tree,
 
1243
                                            source_branch=br_from)
894
1244
                branch = dir.open_branch()
895
1245
            except errors.NoSuchRevision:
896
1246
                to_transport.delete_tree('.')
897
 
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
 
1247
                msg = "The branch %s has no revision %s." % (from_location,
 
1248
                    revision)
898
1249
                raise errors.BzrCommandError(msg)
899
 
            if name:
900
 
                branch.control_files.put_utf8('branch-name', name)
901
1250
            _merge_tags_if_possible(br_from, branch)
902
 
            note('Branched %d revision(s).' % branch.revno())
 
1251
            # If the source branch is stacked, the new branch may
 
1252
            # be stacked whether we asked for that explicitly or not.
 
1253
            # We therefore need a try/except here and not just 'if stacked:'
 
1254
            try:
 
1255
                note('Created new stacked branch referring to %s.' %
 
1256
                    branch.get_stacked_on_url())
 
1257
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
1258
                errors.UnstackableRepositoryFormat), e:
 
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'))
903
1266
        finally:
904
1267
            br_from.unlock()
905
1268
 
911
1274
    the branch found in '.'. This is useful if you have removed the working tree
912
1275
    or if it was never created - i.e. if you pushed the branch to its current
913
1276
    location using SFTP.
914
 
    
 
1277
 
915
1278
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
916
1279
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
917
1280
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
935
1298
                                 "common operations like diff and status without "
936
1299
                                 "such access, and also support local commits."
937
1300
                            ),
 
1301
                     Option('files-from', type=str,
 
1302
                            help="Get file contents from this tree."),
 
1303
                     Option('hardlink',
 
1304
                            help='Hard-link working tree files where possible.'
 
1305
                            ),
938
1306
                     ]
939
1307
    aliases = ['co']
940
1308
 
941
1309
    def run(self, branch_location=None, to_location=None, revision=None,
942
 
            lightweight=False):
943
 
        if revision is None:
944
 
            revision = [None]
945
 
        elif len(revision) > 1:
946
 
            raise errors.BzrCommandError(
947
 
                'bzr checkout --revision takes exactly 1 revision value')
 
1310
            lightweight=False, files_from=None, hardlink=False):
948
1311
        if branch_location is None:
949
1312
            branch_location = osutils.getcwd()
950
1313
            to_location = branch_location
951
 
        source = Branch.open(branch_location)
952
 
        if len(revision) == 1 and revision[0] is not None:
953
 
            revision_id = _mod_revision.ensure_null(
954
 
                revision[0].in_history(source)[1])
 
1314
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
 
1315
            branch_location)
 
1316
        revision = _get_one_revision('checkout', revision)
 
1317
        if files_from is not None:
 
1318
            accelerator_tree = WorkingTree.open(files_from)
 
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) ==
966
1332
            except errors.NoWorkingTree:
967
1333
                source.bzrdir.create_workingtree(revision_id)
968
1334
                return
969
 
        source.create_checkout(to_location, revision_id, lightweight)
 
1335
        source.create_checkout(to_location, revision_id, lightweight,
 
1336
                               accelerator_tree, hardlink)
970
1337
 
971
1338
 
972
1339
class cmd_renames(Command):
988
1355
            old_tree.lock_read()
989
1356
            try:
990
1357
                old_inv = old_tree.inventory
991
 
                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)
992
1366
                renames.sort()
993
1367
                for old_name, new_name in renames:
994
1368
                    self.outf.write("%s => %s\n" % (old_name, new_name))
1000
1374
 
1001
1375
class cmd_update(Command):
1002
1376
    """Update a tree to have the latest code committed to its branch.
1003
 
    
 
1377
 
1004
1378
    This will perform a merge into the working tree, and may generate
1005
 
    conflicts. If you have any local changes, you will still 
 
1379
    conflicts. If you have any local changes, you will still
1006
1380
    need to commit them after the update for the update to be complete.
1007
 
    
1008
 
    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
1009
1383
    'bzr revert' instead of 'bzr commit' after the update.
1010
1384
    """
1011
1385
 
1033
1407
                    revno = tree.branch.revision_id_to_revno(last_rev)
1034
1408
                    note("Tree is up to date at revision %d." % (revno,))
1035
1409
                    return 0
 
1410
            view_info = _get_view_info_for_change_reporter(tree)
1036
1411
            conflicts = tree.update(
1037
 
                delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1038
 
                possible_transports=possible_transports)
 
1412
                delta._ChangeReporter(unversioned_filter=tree.is_ignored,
 
1413
                view_info=view_info), possible_transports=possible_transports)
1039
1414
            revno = tree.branch.revision_id_to_revno(
1040
1415
                _mod_revision.ensure_null(tree.last_revision()))
1041
1416
            note('Updated to revision %d.' % (revno,))
1054
1429
    """Show information about a working tree, branch or repository.
1055
1430
 
1056
1431
    This command will show all known locations and formats associated to the
1057
 
    tree, branch or repository.  Statistical information is included with
1058
 
    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.
1059
1437
 
1060
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
1061
1455
    """
1062
1456
    _see_also = ['revno', 'working-trees', 'repositories']
1063
1457
    takes_args = ['location?']
1064
1458
    takes_options = ['verbose']
 
1459
    encoding_type = 'replace'
1065
1460
 
1066
1461
    @display_command
1067
1462
    def run(self, location=None, verbose=False):
1068
1463
        if verbose:
1069
 
            noise_level = 2
 
1464
            noise_level = get_verbosity_level()
1070
1465
        else:
1071
1466
            noise_level = 0
1072
1467
        from bzrlib.info import show_bzrdir_info
1073
1468
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1074
 
                         verbose=noise_level)
 
1469
                         verbose=noise_level, outfile=self.outf)
1075
1470
 
1076
1471
 
1077
1472
class cmd_remove(Command):
1078
1473
    """Remove files or directories.
1079
1474
 
1080
 
    This makes bzr stop tracking changes to the specified files and
1081
 
    delete them if they can easily be recovered using revert.
1082
 
 
1083
 
    You can specify one or more files, and/or --new.  If you specify --new,
1084
 
    only 'added' files will be removed.  If you specify both, then new files
1085
 
    in the specified directories will be removed.  If the directories are
1086
 
    also new, they will also be removed.
 
1475
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1476
    them if they can easily be recovered using revert. If no options or
 
1477
    parameters are given bzr will scan for files that are being tracked by bzr
 
1478
    but missing in your tree and stop tracking them for you.
1087
1479
    """
1088
1480
    takes_args = ['file*']
1089
1481
    takes_options = ['verbose',
1090
 
        Option('new', help='Remove newly-added files.'),
 
1482
        Option('new', help='Only remove files that have never been committed.'),
1091
1483
        RegistryOption.from_kwargs('file-deletion-strategy',
1092
1484
            'The file deletion mode to be used.',
1093
1485
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1094
1486
            safe='Only delete files if they can be'
1095
1487
                 ' safely recovered (default).',
1096
 
            keep="Don't delete any files.",
 
1488
            keep='Delete from bzr but leave the working copy.',
1097
1489
            force='Delete all the specified files, even if they can not be '
1098
1490
                'recovered and even if they are non-empty directories.')]
1099
 
    aliases = ['rm']
 
1491
    aliases = ['rm', 'del']
1100
1492
    encoding_type = 'replace'
1101
1493
 
1102
1494
    def run(self, file_list, verbose=False, new=False,
1105
1497
 
1106
1498
        if file_list is not None:
1107
1499
            file_list = [f for f in file_list]
1108
 
        elif not new:
1109
 
            raise errors.BzrCommandError('Specify one or more files to'
1110
 
            ' remove, or use --new.')
1111
1500
 
1112
 
        if new:
1113
 
            added = tree.changes_from(tree.basis_tree(),
1114
 
                specific_files=file_list).added
1115
 
            file_list = sorted([f[0] for f in added], reverse=True)
1116
 
            if len(file_list) == 0:
1117
 
                raise errors.BzrCommandError('No matching files.')
1118
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1119
 
            keep_files=file_deletion_strategy=='keep',
1120
 
            force=file_deletion_strategy=='force')
 
1501
        tree.lock_write()
 
1502
        try:
 
1503
            # Heuristics should probably all move into tree.remove_smart or
 
1504
            # some such?
 
1505
            if new:
 
1506
                added = tree.changes_from(tree.basis_tree(),
 
1507
                    specific_files=file_list).added
 
1508
                file_list = sorted([f[0] for f in added], reverse=True)
 
1509
                if len(file_list) == 0:
 
1510
                    raise errors.BzrCommandError('No matching files.')
 
1511
            elif file_list is None:
 
1512
                # missing files show up in iter_changes(basis) as
 
1513
                # versioned-with-no-kind.
 
1514
                missing = []
 
1515
                for change in tree.iter_changes(tree.basis_tree()):
 
1516
                    # Find paths in the working tree that have no kind:
 
1517
                    if change[1][1] is not None and change[6][1] is None:
 
1518
                        missing.append(change[1][1])
 
1519
                file_list = sorted(missing, reverse=True)
 
1520
                file_deletion_strategy = 'keep'
 
1521
            tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1522
                keep_files=file_deletion_strategy=='keep',
 
1523
                force=file_deletion_strategy=='force')
 
1524
        finally:
 
1525
            tree.unlock()
1121
1526
 
1122
1527
 
1123
1528
class cmd_file_id(Command):
1169
1574
 
1170
1575
    This can correct data mismatches that may have been caused by
1171
1576
    previous ghost operations or bzr upgrades. You should only
1172
 
    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
1173
1578
    advises you to run it.
1174
1579
 
1175
1580
    If a second branch is provided, cross-branch reconciliation is
1177
1582
    id which was not present in very early bzr versions is represented
1178
1583
    correctly in both branches.
1179
1584
 
1180
 
    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
1181
1586
    a potential saving in disk space or performance gain.
1182
1587
 
1183
1588
    The branch *MUST* be on a listable system such as local disk or sftp.
1228
1633
            last_revision = wt.last_revision()
1229
1634
 
1230
1635
        revision_ids = b.repository.get_ancestry(last_revision)
1231
 
        assert revision_ids[0] is None
1232
1636
        revision_ids.pop(0)
1233
1637
        for revision_id in revision_ids:
1234
1638
            self.outf.write(revision_id + '\n')
1240
1644
    Use this to create an empty branch, or before importing an
1241
1645
    existing project.
1242
1646
 
1243
 
    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
1244
1648
    the history of the branch will be stored in the repository.  Otherwise
1245
1649
    init creates a standalone branch which carries its own history
1246
1650
    in the .bzr directory.
1254
1658
        bzr init
1255
1659
        bzr add .
1256
1660
        bzr status
1257
 
        bzr commit -m 'imported project'
 
1661
        bzr commit -m "imported project"
1258
1662
    """
1259
1663
 
1260
1664
    _see_also = ['init-repository', 'branch', 'checkout']
1266
1670
         RegistryOption('format',
1267
1671
                help='Specify a format for this branch. '
1268
1672
                'See "help formats".',
1269
 
                registry=bzrdir.format_registry,
1270
 
                converter=bzrdir.format_registry.make_bzrdir,
 
1673
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1674
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1271
1675
                value_switches=True,
1272
 
                title="Branch Format",
 
1676
                title="Branch format",
1273
1677
                ),
1274
1678
         Option('append-revisions-only',
1275
1679
                help='Never change revnos or the existing log.'
1298
1702
                    "\nYou may supply --create-prefix to create all"
1299
1703
                    " leading parent directories."
1300
1704
                    % location)
1301
 
            _create_prefix(to_transport)
 
1705
            to_transport.create_prefix()
1302
1706
 
1303
1707
        try:
1304
 
            existing_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
 
1708
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1305
1709
        except errors.NotBranchError:
1306
1710
            # really a NotBzrDir error...
1307
1711
            create_branch = bzrdir.BzrDir.create_branch_convenience
1308
1712
            branch = create_branch(to_transport.base, format=format,
1309
1713
                                   possible_transports=[to_transport])
 
1714
            a_bzrdir = branch.bzrdir
1310
1715
        else:
1311
1716
            from bzrlib.transport.local import LocalTransport
1312
 
            if existing_bzrdir.has_branch():
 
1717
            if a_bzrdir.has_branch():
1313
1718
                if (isinstance(to_transport, LocalTransport)
1314
 
                    and not existing_bzrdir.has_workingtree()):
 
1719
                    and not a_bzrdir.has_workingtree()):
1315
1720
                        raise errors.BranchExistsWithoutWorkingTree(location)
1316
1721
                raise errors.AlreadyBranchError(location)
1317
 
            else:
1318
 
                branch = existing_bzrdir.create_branch()
1319
 
                existing_bzrdir.create_workingtree()
 
1722
            branch = a_bzrdir.create_branch()
 
1723
            a_bzrdir.create_workingtree()
1320
1724
        if append_revisions_only:
1321
1725
            try:
1322
1726
                branch.set_append_revisions_only(True)
1323
1727
            except errors.UpgradeRequired:
1324
1728
                raise errors.BzrCommandError('This branch format cannot be set'
1325
 
                    ' to append-revisions-only.  Try --experimental-branch6')
 
1729
                    ' to append-revisions-only.  Try --default.')
 
1730
        if not is_quiet():
 
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)
1326
1748
 
1327
1749
 
1328
1750
class cmd_init_repository(Command):
1352
1774
    takes_options = [RegistryOption('format',
1353
1775
                            help='Specify a format for this repository. See'
1354
1776
                                 ' "bzr help formats" for details.',
1355
 
                            registry=bzrdir.format_registry,
1356
 
                            converter=bzrdir.format_registry.make_bzrdir,
 
1777
                            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1778
                            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1357
1779
                            value_switches=True, title='Repository format'),
1358
1780
                     Option('no-trees',
1359
1781
                             help='Branches in the repository will default to'
1374
1796
        newdir = format.initialize_on_transport(to_transport)
1375
1797
        repo = newdir.create_repository(shared=True)
1376
1798
        repo.set_make_working_trees(not no_trees)
 
1799
        if not is_quiet():
 
1800
            from bzrlib.info import show_bzrdir_info
 
1801
            show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1377
1802
 
1378
1803
 
1379
1804
class cmd_diff(Command):
1380
 
    """Show differences in the working tree or between revisions.
1381
 
    
1382
 
    If files are listed, only the changes in those files are listed.
1383
 
    Otherwise, all changes for the tree are listed.
 
1805
    """Show differences in the working tree, between revisions or branches.
 
1806
 
 
1807
    If no arguments are given, all changes for the current tree are listed.
 
1808
    If files are given, only the changes in those files are listed.
 
1809
    Remote and multiple branches can be compared by using the --old and
 
1810
    --new options. If not provided, the default for both is derived from
 
1811
    the first argument, if any, or the current tree if no arguments are
 
1812
    given.
1384
1813
 
1385
1814
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1386
1815
    produces patches suitable for "patch -p1".
1387
1816
 
 
1817
    :Exit values:
 
1818
        1 - changed
 
1819
        2 - unrepresentable changes
 
1820
        3 - error
 
1821
        0 - no change
 
1822
 
1388
1823
    :Examples:
1389
1824
        Shows the difference in the working tree versus the last commit::
1390
1825
 
1398
1833
 
1399
1834
            bzr diff -r1..2
1400
1835
 
 
1836
        Difference between revision 2 and revision 1 for branch xxx::
 
1837
 
 
1838
            bzr diff -r1..2 xxx
 
1839
 
 
1840
        Show just the differences for file NEWS::
 
1841
 
 
1842
            bzr diff NEWS
 
1843
 
 
1844
        Show the differences in working tree xxx for file NEWS::
 
1845
 
 
1846
            bzr diff xxx/NEWS
 
1847
 
 
1848
        Show the differences from branch xxx to this working tree:
 
1849
 
 
1850
            bzr diff --old xxx
 
1851
 
 
1852
        Show the differences between two branches for file NEWS::
 
1853
 
 
1854
            bzr diff --old xxx --new yyy NEWS
 
1855
 
1401
1856
        Same as 'bzr diff' but prefix paths with old/ and new/::
1402
1857
 
1403
1858
            bzr diff --prefix old/:new/
1404
 
 
1405
 
        Show the differences between the two working trees::
1406
 
 
1407
 
            bzr diff bzr.mine bzr.dev
1408
 
 
1409
 
        Show just the differences for 'foo.c'::
1410
 
 
1411
 
            bzr diff foo.c
1412
1859
    """
1413
 
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
1414
 
    #       or a graphical diff.
1415
 
 
1416
 
    # TODO: Python difflib is not exactly the same as unidiff; should
1417
 
    #       either fix it up or prefer to use an external diff.
1418
 
 
1419
 
    # TODO: Selected-file diff is inefficient and doesn't show you
1420
 
    #       deleted files.
1421
 
 
1422
 
    # TODO: This probably handles non-Unix newlines poorly.
1423
 
 
1424
1860
    _see_also = ['status']
1425
1861
    takes_args = ['file*']
1426
1862
    takes_options = [
1430
1866
               short_name='p',
1431
1867
               help='Set prefixes added to old and new filenames, as '
1432
1868
                    'two values separated by a colon. (eg "old/:new/").'),
 
1869
        Option('old',
 
1870
            help='Branch/tree to compare from.',
 
1871
            type=unicode,
 
1872
            ),
 
1873
        Option('new',
 
1874
            help='Branch/tree to compare to.',
 
1875
            type=unicode,
 
1876
            ),
1433
1877
        'revision',
1434
1878
        'change',
 
1879
        Option('using',
 
1880
            help='Use this command to compare files.',
 
1881
            type=unicode,
 
1882
            ),
1435
1883
        ]
1436
1884
    aliases = ['di', 'dif']
1437
1885
    encoding_type = 'exact'
1438
1886
 
1439
1887
    @display_command
1440
1888
    def run(self, revision=None, file_list=None, diff_options=None,
1441
 
            prefix=None):
1442
 
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
 
1889
            prefix=None, old=None, new=None, using=None):
 
1890
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1443
1891
 
1444
1892
        if (prefix is None) or (prefix == '0'):
1445
1893
            # diff -p0 format
1459
1907
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1460
1908
                                         ' one or two revision specifiers')
1461
1909
 
1462
 
        try:
1463
 
            tree1, file_list = internal_tree_files(file_list)
1464
 
            tree2 = None
1465
 
            b = None
1466
 
            b2 = None
1467
 
        except errors.FileInWrongBranch:
1468
 
            if len(file_list) != 2:
1469
 
                raise errors.BzrCommandError("Files are in different branches")
1470
 
 
1471
 
            tree1, file1 = WorkingTree.open_containing(file_list[0])
1472
 
            tree2, file2 = WorkingTree.open_containing(file_list[1])
1473
 
            if file1 != "" or file2 != "":
1474
 
                # FIXME diff those two files. rbc 20051123
1475
 
                raise errors.BzrCommandError("Files are in different branches")
1476
 
            file_list = None
1477
 
        except errors.NotBranchError:
1478
 
            if (revision is not None and len(revision) == 2
1479
 
                and not revision[0].needs_branch()
1480
 
                and not revision[1].needs_branch()):
1481
 
                # If both revision specs include a branch, we can
1482
 
                # diff them without needing a local working tree
1483
 
                tree1, tree2 = None, None
1484
 
            else:
1485
 
                raise
1486
 
 
1487
 
        if tree2 is not None:
1488
 
            if revision is not None:
1489
 
                # FIXME: but there should be a clean way to diff between
1490
 
                # non-default versions of two trees, it's not hard to do
1491
 
                # internally...
1492
 
                raise errors.BzrCommandError(
1493
 
                        "Sorry, diffing arbitrary revisions across branches "
1494
 
                        "is not implemented yet")
1495
 
            return show_diff_trees(tree1, tree2, sys.stdout, 
1496
 
                                   specific_files=file_list,
1497
 
                                   external_diff_options=diff_options,
1498
 
                                   old_label=old_label, new_label=new_label)
1499
 
 
1500
 
        return diff_cmd_helper(tree1, file_list, diff_options,
1501
 
                               revision_specs=revision,
1502
 
                               old_label=old_label, new_label=new_label)
 
1910
        old_tree, new_tree, specific_files, extra_trees = \
 
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,
 
1914
                               specific_files=specific_files,
 
1915
                               external_diff_options=diff_options,
 
1916
                               old_label=old_label, new_label=new_label,
 
1917
                               extra_trees=extra_trees, using=using)
1503
1918
 
1504
1919
 
1505
1920
class cmd_deleted(Command):
1541
1956
 
1542
1957
    hidden = True
1543
1958
    _see_also = ['status', 'ls']
 
1959
    takes_options = [
 
1960
            Option('null',
 
1961
                   help='Write an ascii NUL (\\0) separator '
 
1962
                   'between files rather than a newline.')
 
1963
            ]
1544
1964
 
1545
1965
    @display_command
1546
 
    def run(self):
 
1966
    def run(self, null=False):
1547
1967
        tree = WorkingTree.open_containing(u'.')[0]
1548
1968
        td = tree.changes_from(tree.basis_tree())
1549
1969
        for path, id, kind, text_modified, meta_modified in td.modified:
1550
 
            self.outf.write(path + '\n')
 
1970
            if null:
 
1971
                self.outf.write(path + '\0')
 
1972
            else:
 
1973
                self.outf.write(osutils.quotefn(path) + '\n')
1551
1974
 
1552
1975
 
1553
1976
class cmd_added(Command):
1556
1979
 
1557
1980
    hidden = True
1558
1981
    _see_also = ['status', 'ls']
 
1982
    takes_options = [
 
1983
            Option('null',
 
1984
                   help='Write an ascii NUL (\\0) separator '
 
1985
                   'between files rather than a newline.')
 
1986
            ]
1559
1987
 
1560
1988
    @display_command
1561
 
    def run(self):
 
1989
    def run(self, null=False):
1562
1990
        wt = WorkingTree.open_containing(u'.')[0]
1563
1991
        wt.lock_read()
1564
1992
        try:
1575
2003
                    path = inv.id2path(file_id)
1576
2004
                    if not os.access(osutils.abspath(path), os.F_OK):
1577
2005
                        continue
1578
 
                    self.outf.write(path + '\n')
 
2006
                    if null:
 
2007
                        self.outf.write(path + '\0')
 
2008
                    else:
 
2009
                        self.outf.write(osutils.quotefn(path) + '\n')
1579
2010
            finally:
1580
2011
                basis.unlock()
1581
2012
        finally:
1604
2035
        raise errors.BzrCommandError(msg)
1605
2036
 
1606
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
 
1607
2046
class cmd_log(Command):
1608
 
    """Show log of a branch, file, or directory.
1609
 
 
1610
 
    By default show the log of the branch containing the working directory.
1611
 
 
1612
 
    To request a range of logs, you can use the command -r begin..end
1613
 
    -r revision requests a specific revision, -r ..end or -r begin.. are
1614
 
    also valid.
1615
 
 
1616
 
    :Examples:
1617
 
        Log the current branch::
1618
 
 
1619
 
            bzr log
1620
 
 
1621
 
        Log a file::
1622
 
 
1623
 
            bzr log foo.c
1624
 
 
1625
 
        Log the last 10 revisions of a branch::
1626
 
 
1627
 
            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.
1628
2200
    """
1629
 
 
1630
 
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
1631
 
 
1632
 
    takes_args = ['location?']
 
2201
    takes_args = ['file*']
 
2202
    _see_also = ['log-formats', 'revisionspec']
1633
2203
    takes_options = [
1634
2204
            Option('forward',
1635
2205
                   help='Show from oldest to newest.'),
1636
 
            Option('timezone',
1637
 
                   type=str,
1638
 
                   help='Display timezone as local, original, or utc.'),
 
2206
            'timezone',
1639
2207
            custom_help('verbose',
1640
2208
                   help='Show files changed in each revision.'),
1641
2209
            'show-ids',
1642
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".'),
1643
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),
1644
2222
            Option('message',
1645
2223
                   short_name='m',
1646
2224
                   help='Show revisions whose message matches this '
1647
2225
                        'regular expression.',
1648
2226
                   type=str),
1649
2227
            Option('limit',
 
2228
                   short_name='l',
1650
2229
                   help='Limit the output to the first N revisions.',
1651
2230
                   argname='N',
1652
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.'),
1653
2237
            ]
1654
2238
    encoding_type = 'replace'
1655
2239
 
1656
2240
    @display_command
1657
 
    def run(self, location=None, timezone='original',
 
2241
    def run(self, file_list=None, timezone='original',
1658
2242
            verbose=False,
1659
2243
            show_ids=False,
1660
2244
            forward=False,
1661
2245
            revision=None,
 
2246
            change=None,
1662
2247
            log_format=None,
 
2248
            levels=None,
1663
2249
            message=None,
1664
 
            limit=None):
1665
 
        from bzrlib.log import show_log
1666
 
        assert message is None or isinstance(message, basestring), \
1667
 
            "invalid message argument %r" % message
 
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
            )
1668
2258
        direction = (forward and 'forward') or 'reverse'
1669
 
        
1670
 
        # log everything
1671
 
        file_id = None
1672
 
        if location:
1673
 
            # find the file id to log:
1674
 
 
1675
 
            tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1676
 
                location)
1677
 
            if fp != '':
1678
 
                if tree is None:
1679
 
                    tree = b.basis_tree()
1680
 
                file_id = tree.path2id(fp)
1681
 
                if file_id is None:
1682
 
                    raise errors.BzrCommandError(
1683
 
                        "Path does not have any revision history: %s" %
1684
 
                        location)
1685
 
        else:
1686
 
            # local dir only
1687
 
            # FIXME ? log the current subdir only RBC 20060203 
1688
 
            if revision is not None \
1689
 
                    and len(revision) > 0 and revision[0].get_branch():
1690
 
                location = revision[0].get_branch()
1691
 
            else:
1692
 
                location = '.'
1693
 
            dir, relpath = bzrdir.BzrDir.open_containing(location)
1694
 
            b = dir.open_branch()
1695
 
 
1696
 
        b.lock_read()
 
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
        b = None
1697
2278
        try:
1698
 
            if revision is None:
1699
 
                rev1 = None
1700
 
                rev2 = None
1701
 
            elif len(revision) == 1:
1702
 
                rev1 = rev2 = revision[0].in_history(b)
1703
 
            elif len(revision) == 2:
1704
 
                if revision[1].get_branch() != revision[0].get_branch():
1705
 
                    # b is taken from revision[0].get_branch(), and
1706
 
                    # show_log will use its revision_history. Having
1707
 
                    # different branches will lead to weird behaviors.
1708
 
                    raise errors.BzrCommandError(
1709
 
                        "Log doesn't accept two revisions in different"
1710
 
                        " branches.")
1711
 
                rev1 = revision[0].in_history(b)
1712
 
                rev2 = revision[1].in_history(b)
1713
 
            else:
1714
 
                raise errors.BzrCommandError(
1715
 
                    'bzr log --revision takes one or two values.')
1716
 
 
 
2279
            if file_list:
 
2280
                # find the file ids to log and check for directory filtering
 
2281
                b, file_info_list, rev1, rev2 = _get_info_for_log_files(
 
2282
                    revision, file_list)
 
2283
                for relpath, file_id, kind in file_info_list:
 
2284
                    if file_id is None:
 
2285
                        raise errors.BzrCommandError(
 
2286
                            "Path unknown at end or start of revision range: %s" %
 
2287
                            relpath)
 
2288
                    # If the relpath is the top of the tree, we log everything
 
2289
                    if relpath == '':
 
2290
                        file_ids = []
 
2291
                        break
 
2292
                    else:
 
2293
                        file_ids.append(file_id)
 
2294
                    filter_by_dir = filter_by_dir or (
 
2295
                        kind in ['directory', 'tree-reference'])
 
2296
            else:
 
2297
                # log everything
 
2298
                # FIXME ? log the current subdir only RBC 20060203
 
2299
                if revision is not None \
 
2300
                        and len(revision) > 0 and revision[0].get_branch():
 
2301
                    location = revision[0].get_branch()
 
2302
                else:
 
2303
                    location = '.'
 
2304
                dir, relpath = bzrdir.BzrDir.open_containing(location)
 
2305
                b = dir.open_branch()
 
2306
                b.lock_read()
 
2307
                rev1, rev2 = _get_revision_range(revision, b, self.name())
 
2308
 
 
2309
            # Decide on the type of delta & diff filtering to use
 
2310
            # TODO: add an --all-files option to make this configurable & consistent
 
2311
            if not verbose:
 
2312
                delta_type = None
 
2313
            else:
 
2314
                delta_type = 'full'
 
2315
            if not show_diff:
 
2316
                diff_type = None
 
2317
            elif file_ids:
 
2318
                diff_type = 'partial'
 
2319
            else:
 
2320
                diff_type = 'full'
 
2321
 
 
2322
            # Build the log formatter
1717
2323
            if log_format is None:
1718
2324
                log_format = log.log_formatter_registry.get_default(b)
1719
 
 
1720
2325
            lf = log_format(show_ids=show_ids, to_file=self.outf,
1721
 
                            show_timezone=timezone)
1722
 
 
1723
 
            show_log(b,
1724
 
                     lf,
1725
 
                     file_id,
1726
 
                     verbose=verbose,
1727
 
                     direction=direction,
1728
 
                     start_revision=rev1,
1729
 
                     end_revision=rev2,
1730
 
                     search=message,
1731
 
                     limit=limit)
 
2326
                            show_timezone=timezone,
 
2327
                            delta_format=get_verbosity_level(),
 
2328
                            levels=levels,
 
2329
                            show_advice=levels is None)
 
2330
 
 
2331
            # Choose the algorithm for doing the logging. It's annoying
 
2332
            # having multiple code paths like this but necessary until
 
2333
            # the underlying repository format is faster at generating
 
2334
            # deltas or can provide everything we need from the indices.
 
2335
            # The default algorithm - match-using-deltas - works for
 
2336
            # multiple files and directories and is faster for small
 
2337
            # amounts of history (200 revisions say). However, it's too
 
2338
            # slow for logging a single file in a repository with deep
 
2339
            # history, i.e. > 10K revisions. In the spirit of "do no
 
2340
            # evil when adding features", we continue to use the
 
2341
            # original algorithm - per-file-graph - for the "single
 
2342
            # file that isn't a directory without showing a delta" case.
 
2343
            partial_history = revision and b.repository._format.supports_chks
 
2344
            match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2345
                or delta_type or partial_history)
 
2346
 
 
2347
            # Build the LogRequest and execute it
 
2348
            if len(file_ids) == 0:
 
2349
                file_ids = None
 
2350
            rqst = make_log_request_dict(
 
2351
                direction=direction, specific_fileids=file_ids,
 
2352
                start_revision=rev1, end_revision=rev2, limit=limit,
 
2353
                message_search=message, delta_type=delta_type,
 
2354
                diff_type=diff_type, _match_using_deltas=match_using_deltas)
 
2355
            Logger(b, rqst).show(lf)
1732
2356
        finally:
1733
 
            b.unlock()
1734
 
 
 
2357
            if b is not None:
 
2358
                b.unlock()
 
2359
 
 
2360
 
 
2361
def _get_revision_range(revisionspec_list, branch, command_name):
 
2362
    """Take the input of a revision option and turn it into a revision range.
 
2363
 
 
2364
    It returns RevisionInfo objects which can be used to obtain the rev_id's
 
2365
    of the desired revisions. It does some user input validations.
 
2366
    """
 
2367
    if revisionspec_list is None:
 
2368
        rev1 = None
 
2369
        rev2 = None
 
2370
    elif len(revisionspec_list) == 1:
 
2371
        rev1 = rev2 = revisionspec_list[0].in_history(branch)
 
2372
    elif len(revisionspec_list) == 2:
 
2373
        start_spec = revisionspec_list[0]
 
2374
        end_spec = revisionspec_list[1]
 
2375
        if end_spec.get_branch() != start_spec.get_branch():
 
2376
            # b is taken from revision[0].get_branch(), and
 
2377
            # show_log will use its revision_history. Having
 
2378
            # different branches will lead to weird behaviors.
 
2379
            raise errors.BzrCommandError(
 
2380
                "bzr %s doesn't accept two revisions in different"
 
2381
                " branches." % command_name)
 
2382
        rev1 = start_spec.in_history(branch)
 
2383
        # Avoid loading all of history when we know a missing
 
2384
        # end of range means the last revision ...
 
2385
        if end_spec.spec is None:
 
2386
            last_revno, last_revision_id = branch.last_revision_info()
 
2387
            rev2 = RevisionInfo(branch, last_revno, last_revision_id)
 
2388
        else:
 
2389
            rev2 = end_spec.in_history(branch)
 
2390
    else:
 
2391
        raise errors.BzrCommandError(
 
2392
            'bzr %s --revision takes one or two values.' % command_name)
 
2393
    return rev1, rev2
 
2394
 
 
2395
 
 
2396
def _revision_range_to_revid_range(revision_range):
 
2397
    rev_id1 = None
 
2398
    rev_id2 = None
 
2399
    if revision_range[0] is not None:
 
2400
        rev_id1 = revision_range[0].rev_id
 
2401
    if revision_range[1] is not None:
 
2402
        rev_id2 = revision_range[1].rev_id
 
2403
    return rev_id1, rev_id2
1735
2404
 
1736
2405
def get_log_format(long=False, short=False, line=False, default='long'):
1737
2406
    log_format = default
1756
2425
    @display_command
1757
2426
    def run(self, filename):
1758
2427
        tree, relpath = WorkingTree.open_containing(filename)
 
2428
        file_id = tree.path2id(relpath)
1759
2429
        b = tree.branch
1760
 
        file_id = tree.path2id(relpath)
1761
 
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1762
 
            self.outf.write("%6d %s\n" % (revno, what))
 
2430
        b.lock_read()
 
2431
        try:
 
2432
            touching_revs = log.find_touching_revisions(b, file_id)
 
2433
            for revno, revision_id, what in touching_revs:
 
2434
                self.outf.write("%6d %s\n" % (revno, what))
 
2435
        finally:
 
2436
            b.unlock()
1763
2437
 
1764
2438
 
1765
2439
class cmd_ls(Command):
1768
2442
 
1769
2443
    _see_also = ['status', 'cat']
1770
2444
    takes_args = ['path?']
1771
 
    # TODO: Take a revision or remote path and list that tree instead.
1772
2445
    takes_options = [
1773
2446
            'verbose',
1774
2447
            'revision',
1775
 
            Option('non-recursive',
1776
 
                   help='Don\'t recurse into subdirectories.'),
 
2448
            Option('recursive', short_name='R',
 
2449
                   help='Recurse into subdirectories.'),
1777
2450
            Option('from-root',
1778
2451
                   help='Print paths relative to the root of the branch.'),
1779
2452
            Option('unknown', help='Print unknown files.'),
1780
 
            Option('versioned', help='Print versioned files.'),
 
2453
            Option('versioned', help='Print versioned files.',
 
2454
                   short_name='V'),
1781
2455
            Option('ignored', help='Print ignored files.'),
1782
2456
            Option('null',
1783
2457
                   help='Write an ascii NUL (\\0) separator '
1789
2463
            ]
1790
2464
    @display_command
1791
2465
    def run(self, revision=None, verbose=False,
1792
 
            non_recursive=False, from_root=False,
 
2466
            recursive=False, from_root=False,
1793
2467
            unknown=False, versioned=False, ignored=False,
1794
2468
            null=False, kind=None, show_ids=False, path=None):
1795
2469
 
1804
2478
 
1805
2479
        if path is None:
1806
2480
            fs_path = '.'
1807
 
            prefix = ''
1808
2481
        else:
1809
2482
            if from_root:
1810
2483
                raise errors.BzrCommandError('cannot specify both --from-root'
1811
2484
                                             ' and PATH')
1812
2485
            fs_path = path
1813
 
            prefix = path
1814
2486
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1815
2487
            fs_path)
 
2488
 
 
2489
        # Calculate the prefix to use
 
2490
        prefix = None
1816
2491
        if from_root:
1817
 
            relpath = u''
1818
 
        elif relpath:
1819
 
            relpath += '/'
1820
 
        if revision is not None:
1821
 
            tree = branch.repository.revision_tree(
1822
 
                revision[0].in_history(branch).rev_id)
1823
 
        elif tree is None:
1824
 
            tree = branch.basis_tree()
 
2492
            if relpath:
 
2493
                prefix = relpath + '/'
 
2494
        elif fs_path != '.':
 
2495
            prefix = fs_path + '/'
 
2496
 
 
2497
        if revision is not None or tree is None:
 
2498
            tree = _get_one_revision_tree('ls', revision, branch=branch)
 
2499
 
 
2500
        apply_view = False
 
2501
        if isinstance(tree, WorkingTree) and tree.supports_views():
 
2502
            view_files = tree.views.lookup_view()
 
2503
            if view_files:
 
2504
                apply_view = True
 
2505
                view_str = views.view_display_str(view_files)
 
2506
                note("Ignoring files outside view. View is %s" % view_str)
1825
2507
 
1826
2508
        tree.lock_read()
1827
2509
        try:
1828
 
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1829
 
                if fp.startswith(relpath):
1830
 
                    fp = osutils.pathjoin(prefix, fp[len(relpath):])
1831
 
                    if non_recursive and '/' in fp:
1832
 
                        continue
1833
 
                    if not all and not selection[fc]:
1834
 
                        continue
1835
 
                    if kind is not None and fkind != kind:
1836
 
                        continue
1837
 
                    if verbose:
1838
 
                        kindch = entry.kind_character()
1839
 
                        outstring = '%-8s %s%s' % (fc, fp, kindch)
1840
 
                        if show_ids and fid is not None:
1841
 
                            outstring = "%-50s %s" % (outstring, fid)
1842
 
                        self.outf.write(outstring + '\n')
1843
 
                    elif null:
1844
 
                        self.outf.write(fp + '\0')
1845
 
                        if show_ids:
1846
 
                            if fid is not None:
1847
 
                                self.outf.write(fid)
1848
 
                            self.outf.write('\0')
1849
 
                        self.outf.flush()
1850
 
                    else:
 
2510
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
2511
                from_dir=relpath, recursive=recursive):
 
2512
                # Apply additional masking
 
2513
                if not all and not selection[fc]:
 
2514
                    continue
 
2515
                if kind is not None and fkind != kind:
 
2516
                    continue
 
2517
                if apply_view:
 
2518
                    try:
 
2519
                        if relpath:
 
2520
                            fullpath = osutils.pathjoin(relpath, fp)
 
2521
                        else:
 
2522
                            fullpath = fp
 
2523
                        views.check_path_in_view(tree, fullpath)
 
2524
                    except errors.FileOutsideView:
 
2525
                        continue
 
2526
 
 
2527
                # Output the entry
 
2528
                if prefix:
 
2529
                    fp = osutils.pathjoin(prefix, fp)
 
2530
                kindch = entry.kind_character()
 
2531
                outstring = fp + kindch
 
2532
                ui.ui_factory.clear_term()
 
2533
                if verbose:
 
2534
                    outstring = '%-8s %s' % (fc, outstring)
 
2535
                    if show_ids and fid is not None:
 
2536
                        outstring = "%-50s %s" % (outstring, fid)
 
2537
                    self.outf.write(outstring + '\n')
 
2538
                elif null:
 
2539
                    self.outf.write(fp + '\0')
 
2540
                    if show_ids:
 
2541
                        if fid is not None:
 
2542
                            self.outf.write(fid)
 
2543
                        self.outf.write('\0')
 
2544
                    self.outf.flush()
 
2545
                else:
 
2546
                    if show_ids:
1851
2547
                        if fid is not None:
1852
2548
                            my_id = fid
1853
2549
                        else:
1854
2550
                            my_id = ''
1855
 
                        if show_ids:
1856
 
                            self.outf.write('%-50s %s\n' % (fp, my_id))
1857
 
                        else:
1858
 
                            self.outf.write(fp + '\n')
 
2551
                        self.outf.write('%-50s %s\n' % (outstring, my_id))
 
2552
                    else:
 
2553
                        self.outf.write(outstring + '\n')
1859
2554
        finally:
1860
2555
            tree.unlock()
1861
2556
 
1876
2571
class cmd_ignore(Command):
1877
2572
    """Ignore specified files or patterns.
1878
2573
 
 
2574
    See ``bzr help patterns`` for details on the syntax of patterns.
 
2575
 
1879
2576
    To remove patterns from the ignore list, edit the .bzrignore file.
1880
 
 
1881
 
    Trailing slashes on patterns are ignored. 
1882
 
    If the pattern contains a slash or is a regular expression, it is compared 
1883
 
    to the whole path from the branch root.  Otherwise, it is compared to only
1884
 
    the last component of the path.  To match a file only in the root 
1885
 
    directory, prepend './'.
1886
 
 
1887
 
    Ignore patterns specifying absolute paths are not allowed.
1888
 
 
1889
 
    Ignore patterns may include globbing wildcards such as::
1890
 
 
1891
 
      ? - Matches any single character except '/'
1892
 
      * - Matches 0 or more characters except '/'
1893
 
      /**/ - Matches 0 or more directories in a path
1894
 
      [a-z] - Matches a single character from within a group of characters
1895
 
 
1896
 
    Ignore patterns may also be Python regular expressions.  
1897
 
    Regular expression ignore patterns are identified by a 'RE:' prefix 
1898
 
    followed by the regular expression.  Regular expression ignore patterns
1899
 
    may not include named or numbered groups.
1900
 
 
1901
 
    Note: ignore patterns containing shell wildcards must be quoted from 
 
2577
    After adding, editing or deleting that file either indirectly by
 
2578
    using this command or directly by using an editor, be sure to commit
 
2579
    it.
 
2580
 
 
2581
    Note: ignore patterns containing shell wildcards must be quoted from
1902
2582
    the shell on Unix.
1903
2583
 
1904
2584
    :Examples:
1908
2588
 
1909
2589
        Ignore class files in all directories::
1910
2590
 
1911
 
            bzr ignore '*.class'
1912
 
 
1913
 
        Ignore .o files under the lib directory::
1914
 
 
1915
 
            bzr ignore 'lib/**/*.o'
1916
 
 
1917
 
        Ignore .o files under the lib directory::
1918
 
 
1919
 
            bzr ignore 'RE:lib/.*\.o'
 
2591
            bzr ignore "*.class"
 
2592
 
 
2593
        Ignore .o files under the lib directory::
 
2594
 
 
2595
            bzr ignore "lib/**/*.o"
 
2596
 
 
2597
        Ignore .o files under the lib directory::
 
2598
 
 
2599
            bzr ignore "RE:lib/.*\.o"
 
2600
 
 
2601
        Ignore everything but the "debian" toplevel directory::
 
2602
 
 
2603
            bzr ignore "RE:(?!debian/).*"
1920
2604
    """
1921
2605
 
1922
 
    _see_also = ['status', 'ignored']
 
2606
    _see_also = ['status', 'ignored', 'patterns']
1923
2607
    takes_args = ['name_pattern*']
1924
2608
    takes_options = [
1925
2609
        Option('old-default-rules',
1926
2610
               help='Write out the ignore rules bzr < 0.9 always used.')
1927
2611
        ]
1928
 
    
 
2612
 
1929
2613
    def run(self, name_pattern_list=None, old_default_rules=None):
1930
 
        from bzrlib.atomicfile import AtomicFile
 
2614
        from bzrlib import ignores
1931
2615
        if old_default_rules is not None:
1932
2616
            # dump the rules and exit
1933
2617
            for pattern in ignores.OLD_DEFAULTS:
1936
2620
        if not name_pattern_list:
1937
2621
            raise errors.BzrCommandError("ignore requires at least one "
1938
2622
                                  "NAME_PATTERN or --old-default-rules")
1939
 
        name_pattern_list = [globbing.normalize_pattern(p) 
 
2623
        name_pattern_list = [globbing.normalize_pattern(p)
1940
2624
                             for p in name_pattern_list]
1941
2625
        for name_pattern in name_pattern_list:
1942
 
            if (name_pattern[0] == '/' or 
 
2626
            if (name_pattern[0] == '/' or
1943
2627
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
1944
2628
                raise errors.BzrCommandError(
1945
2629
                    "NAME_PATTERN should not be an absolute path")
1946
2630
        tree, relpath = WorkingTree.open_containing(u'.')
1947
 
        ifn = tree.abspath('.bzrignore')
1948
 
        if os.path.exists(ifn):
1949
 
            f = open(ifn, 'rt')
1950
 
            try:
1951
 
                igns = f.read().decode('utf-8')
1952
 
            finally:
1953
 
                f.close()
1954
 
        else:
1955
 
            igns = ''
1956
 
 
1957
 
        # TODO: If the file already uses crlf-style termination, maybe
1958
 
        # we should use that for the newly added lines?
1959
 
 
1960
 
        if igns and igns[-1] != '\n':
1961
 
            igns += '\n'
1962
 
        for name_pattern in name_pattern_list:
1963
 
            igns += name_pattern + '\n'
1964
 
 
1965
 
        f = AtomicFile(ifn, 'wb')
1966
 
        try:
1967
 
            f.write(igns.encode('utf-8'))
1968
 
            f.commit()
1969
 
        finally:
1970
 
            f.close()
1971
 
 
1972
 
        if not tree.path2id('.bzrignore'):
1973
 
            tree.add(['.bzrignore'])
1974
 
 
 
2631
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
1975
2632
        ignored = globbing.Globster(name_pattern_list)
1976
2633
        matches = []
1977
2634
        tree.lock_read()
1984
2641
        tree.unlock()
1985
2642
        if len(matches) > 0:
1986
2643
            print "Warning: the following files are version controlled and" \
1987
 
                  " match your ignore pattern:\n%s" % ("\n".join(matches),)
 
2644
                  " match your ignore pattern:\n%s" \
 
2645
                  "\nThese files will continue to be version controlled" \
 
2646
                  " unless you 'bzr remove' them." % ("\n".join(matches),)
 
2647
 
1988
2648
 
1989
2649
class cmd_ignored(Command):
1990
2650
    """List ignored files and the patterns that matched them.
 
2651
 
 
2652
    List all the ignored files and the ignore pattern that caused the file to
 
2653
    be ignored.
 
2654
 
 
2655
    Alternatively, to list just the files::
 
2656
 
 
2657
        bzr ls --ignored
1991
2658
    """
1992
2659
 
1993
 
    _see_also = ['ignore']
 
2660
    encoding_type = 'replace'
 
2661
    _see_also = ['ignore', 'ls']
 
2662
 
1994
2663
    @display_command
1995
2664
    def run(self):
1996
2665
        tree = WorkingTree.open_containing(u'.')[0]
2001
2670
                    continue
2002
2671
                ## XXX: Slightly inefficient since this was already calculated
2003
2672
                pat = tree.is_ignored(path)
2004
 
                print '%-50s %s' % (path, pat)
 
2673
                self.outf.write('%-50s %s\n' % (path, pat))
2005
2674
        finally:
2006
2675
            tree.unlock()
2007
2676
 
2014
2683
    """
2015
2684
    hidden = True
2016
2685
    takes_args = ['revno']
2017
 
    
 
2686
 
2018
2687
    @display_command
2019
2688
    def run(self, revno):
2020
2689
        try:
2053
2722
         zip                          .zip
2054
2723
      =================       =========================
2055
2724
    """
2056
 
    takes_args = ['dest', 'branch?']
 
2725
    takes_args = ['dest', 'branch_or_subdir?']
2057
2726
    takes_options = [
2058
2727
        Option('format',
2059
2728
               help="Type of file to export to.",
2060
2729
               type=unicode),
2061
2730
        'revision',
 
2731
        Option('filters', help='Apply content filters to export the '
 
2732
                'convenient form.'),
2062
2733
        Option('root',
2063
2734
               type=str,
2064
2735
               help="Name of the root directory inside the exported file."),
2065
2736
        ]
2066
 
    def run(self, dest, branch=None, revision=None, format=None, root=None):
 
2737
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
 
2738
        root=None, filters=False):
2067
2739
        from bzrlib.export import export
2068
2740
 
2069
 
        if branch is None:
 
2741
        if branch_or_subdir is None:
2070
2742
            tree = WorkingTree.open_containing(u'.')[0]
2071
2743
            b = tree.branch
2072
 
        else:
2073
 
            b = Branch.open(branch)
2074
 
            
2075
 
        if revision is None:
2076
 
            # should be tree.last_revision  FIXME
2077
 
            rev_id = b.last_revision()
2078
 
        else:
2079
 
            if len(revision) != 1:
2080
 
                raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2081
 
            rev_id = revision[0].in_history(b).rev_id
2082
 
        t = b.repository.revision_tree(rev_id)
 
2744
            subdir = None
 
2745
        else:
 
2746
            b, subdir = Branch.open_containing(branch_or_subdir)
 
2747
            tree = None
 
2748
 
 
2749
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2083
2750
        try:
2084
 
            export(t, dest, format, root)
 
2751
            export(rev_tree, dest, format, root, subdir, filtered=filters)
2085
2752
        except errors.NoSuchExportFormat, e:
2086
2753
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2087
2754
 
2092
2759
    If no revision is nominated, the last revision is used.
2093
2760
 
2094
2761
    Note: Take care to redirect standard output when using this command on a
2095
 
    binary file. 
 
2762
    binary file.
2096
2763
    """
2097
2764
 
2098
2765
    _see_also = ['ls']
2099
2766
    takes_options = [
2100
2767
        Option('name-from-revision', help='The path name in the old tree.'),
 
2768
        Option('filters', help='Apply content filters to display the '
 
2769
                'convenience form.'),
2101
2770
        'revision',
2102
2771
        ]
2103
2772
    takes_args = ['filename']
2104
2773
    encoding_type = 'exact'
2105
2774
 
2106
2775
    @display_command
2107
 
    def run(self, filename, revision=None, name_from_revision=False):
 
2776
    def run(self, filename, revision=None, name_from_revision=False,
 
2777
            filters=False):
2108
2778
        if revision is not None and len(revision) != 1:
2109
2779
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2110
 
                                        " one number")
2111
 
 
2112
 
        tree = None
 
2780
                                         " one revision specifier")
 
2781
        tree, branch, relpath = \
 
2782
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2783
        branch.lock_read()
2113
2784
        try:
2114
 
            tree, b, relpath = \
2115
 
                    bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2116
 
        except errors.NotBranchError:
2117
 
            pass
 
2785
            return self._run(tree, branch, relpath, filename, revision,
 
2786
                             name_from_revision, filters)
 
2787
        finally:
 
2788
            branch.unlock()
2118
2789
 
2119
 
        if revision is not None and revision[0].get_branch() is not None:
2120
 
            b = Branch.open(revision[0].get_branch())
 
2790
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
 
2791
        filtered):
2121
2792
        if tree is None:
2122
2793
            tree = b.basis_tree()
2123
 
        if revision is None:
2124
 
            revision_id = b.last_revision()
2125
 
        else:
2126
 
            revision_id = revision[0].in_history(b).rev_id
 
2794
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2127
2795
 
2128
 
        cur_file_id = tree.path2id(relpath)
2129
 
        rev_tree = b.repository.revision_tree(revision_id)
2130
2796
        old_file_id = rev_tree.path2id(relpath)
2131
 
        
 
2797
 
2132
2798
        if name_from_revision:
 
2799
            # Try in revision if requested
2133
2800
            if old_file_id is None:
2134
 
                raise errors.BzrCommandError("%r is not present in revision %s"
2135
 
                                                % (filename, revision_id))
 
2801
                raise errors.BzrCommandError(
 
2802
                    "%r is not present in revision %s" % (
 
2803
                        filename, rev_tree.get_revision_id()))
2136
2804
            else:
2137
 
                rev_tree.print_file(old_file_id)
2138
 
        elif cur_file_id is not None:
2139
 
            rev_tree.print_file(cur_file_id)
2140
 
        elif old_file_id is not None:
2141
 
            rev_tree.print_file(old_file_id)
2142
 
        else:
2143
 
            raise errors.BzrCommandError("%r is not present in revision %s" %
2144
 
                                         (filename, revision_id))
 
2805
                content = rev_tree.get_file_text(old_file_id)
 
2806
        else:
 
2807
            cur_file_id = tree.path2id(relpath)
 
2808
            found = False
 
2809
            if cur_file_id is not None:
 
2810
                # Then try with the actual file id
 
2811
                try:
 
2812
                    content = rev_tree.get_file_text(cur_file_id)
 
2813
                    found = True
 
2814
                except errors.NoSuchId:
 
2815
                    # The actual file id didn't exist at that time
 
2816
                    pass
 
2817
            if not found and old_file_id is not None:
 
2818
                # Finally try with the old file id
 
2819
                content = rev_tree.get_file_text(old_file_id)
 
2820
                found = True
 
2821
            if not found:
 
2822
                # Can't be found anywhere
 
2823
                raise errors.BzrCommandError(
 
2824
                    "%r is not present in revision %s" % (
 
2825
                        filename, rev_tree.get_revision_id()))
 
2826
        if filtered:
 
2827
            from bzrlib.filters import (
 
2828
                ContentFilterContext,
 
2829
                filtered_output_bytes,
 
2830
                )
 
2831
            filters = rev_tree._content_filter_stack(relpath)
 
2832
            chunks = content.splitlines(True)
 
2833
            content = filtered_output_bytes(chunks, filters,
 
2834
                ContentFilterContext(relpath, rev_tree))
 
2835
            self.outf.writelines(content)
 
2836
        else:
 
2837
            self.outf.write(content)
2145
2838
 
2146
2839
 
2147
2840
class cmd_local_time_offset(Command):
2148
2841
    """Show the offset in seconds from GMT to local time."""
2149
 
    hidden = True    
 
2842
    hidden = True
2150
2843
    @display_command
2151
2844
    def run(self):
2152
2845
        print osutils.local_time_offset()
2155
2848
 
2156
2849
class cmd_commit(Command):
2157
2850
    """Commit changes into a new revision.
2158
 
    
2159
 
    If no arguments are given, the entire tree is committed.
2160
 
 
2161
 
    If selected files are specified, only changes to those files are
2162
 
    committed.  If a directory is specified then the directory and everything 
2163
 
    within it is committed.
2164
 
 
2165
 
    If author of the change is not the same person as the committer, you can
2166
 
    specify the author's name using the --author option. The name should be
2167
 
    in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2168
 
 
2169
 
    A selected-file commit may fail in some cases where the committed
2170
 
    tree would be invalid. Consider::
2171
 
 
2172
 
      bzr init foo
2173
 
      mkdir foo/bar
2174
 
      bzr add foo/bar
2175
 
      bzr commit foo -m "committing foo"
2176
 
      bzr mv foo/bar foo/baz
2177
 
      mkdir foo/bar
2178
 
      bzr add foo/bar
2179
 
      bzr commit foo/bar -m "committing bar but not baz"
2180
 
 
2181
 
    In the example above, the last commit will fail by design. This gives
2182
 
    the user the opportunity to decide whether they want to commit the
2183
 
    rename at the same time, separately first, or not at all. (As a general
2184
 
    rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2185
 
 
2186
 
    Note: A selected-file commit after a merge is not yet supported.
 
2851
 
 
2852
    An explanatory message needs to be given for each commit. This is
 
2853
    often done by using the --message option (getting the message from the
 
2854
    command line) or by using the --file option (getting the message from
 
2855
    a file). If neither of these options is given, an editor is opened for
 
2856
    the user to enter the message. To see the changed files in the
 
2857
    boilerplate text loaded into the editor, use the --show-diff option.
 
2858
 
 
2859
    By default, the entire tree is committed and the person doing the
 
2860
    commit is assumed to be the author. These defaults can be overridden
 
2861
    as explained below.
 
2862
 
 
2863
    :Selective commits:
 
2864
 
 
2865
      If selected files are specified, only changes to those files are
 
2866
      committed.  If a directory is specified then the directory and
 
2867
      everything within it is committed.
 
2868
  
 
2869
      When excludes are given, they take precedence over selected files.
 
2870
      For example, to commit only changes within foo, but not changes
 
2871
      within foo/bar::
 
2872
  
 
2873
        bzr commit foo -x foo/bar
 
2874
  
 
2875
      A selective commit after a merge is not yet supported.
 
2876
 
 
2877
    :Custom authors:
 
2878
 
 
2879
      If the author of the change is not the same person as the committer,
 
2880
      you can specify the author's name using the --author option. The
 
2881
      name should be in the same format as a committer-id, e.g.
 
2882
      "John Doe <jdoe@example.com>". If there is more than one author of
 
2883
      the change you can specify the option multiple times, once for each
 
2884
      author.
 
2885
  
 
2886
    :Checks:
 
2887
 
 
2888
      A common mistake is to forget to add a new file or directory before
 
2889
      running the commit command. The --strict option checks for unknown
 
2890
      files and aborts the commit if any are found. More advanced pre-commit
 
2891
      checks can be implemented by defining hooks. See ``bzr help hooks``
 
2892
      for details.
 
2893
 
 
2894
    :Things to note:
 
2895
 
 
2896
      If you accidentially commit the wrong changes or make a spelling
 
2897
      mistake in the commit message say, you can use the uncommit command
 
2898
      to undo it. See ``bzr help uncommit`` for details.
 
2899
 
 
2900
      Hooks can also be configured to run after a commit. This allows you
 
2901
      to trigger updates to external systems like bug trackers. The --fixes
 
2902
      option can be used to record the association between a revision and
 
2903
      one or more bugs. See ``bzr help bugs`` for details.
 
2904
 
 
2905
      A selective commit may fail in some cases where the committed
 
2906
      tree would be invalid. Consider::
 
2907
  
 
2908
        bzr init foo
 
2909
        mkdir foo/bar
 
2910
        bzr add foo/bar
 
2911
        bzr commit foo -m "committing foo"
 
2912
        bzr mv foo/bar foo/baz
 
2913
        mkdir foo/bar
 
2914
        bzr add foo/bar
 
2915
        bzr commit foo/bar -m "committing bar but not baz"
 
2916
  
 
2917
      In the example above, the last commit will fail by design. This gives
 
2918
      the user the opportunity to decide whether they want to commit the
 
2919
      rename at the same time, separately first, or not at all. (As a general
 
2920
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2187
2921
    """
2188
2922
    # TODO: Run hooks on tree to-be-committed, and after commit.
2189
2923
 
2194
2928
 
2195
2929
    # XXX: verbose currently does nothing
2196
2930
 
2197
 
    _see_also = ['bugs', 'uncommit']
 
2931
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
2198
2932
    takes_args = ['selected*']
2199
2933
    takes_options = [
 
2934
            ListOption('exclude', type=str, short_name='x',
 
2935
                help="Do not consider changes made to a given path."),
2200
2936
            Option('message', type=unicode,
2201
2937
                   short_name='m',
2202
2938
                   help="Description of the new revision."),
2211
2947
                    help="Refuse to commit if there are unknown "
2212
2948
                    "files in the working tree."),
2213
2949
             ListOption('fixes', type=str,
2214
 
                    help="Mark a bug as being fixed by this revision."),
2215
 
             Option('author', type=str,
 
2950
                    help="Mark a bug as being fixed by this revision "
 
2951
                         "(see \"bzr help bugs\")."),
 
2952
             ListOption('author', type=unicode,
2216
2953
                    help="Set the author's name, if it's different "
2217
2954
                         "from the committer."),
2218
2955
             Option('local',
2227
2964
             ]
2228
2965
    aliases = ['ci', 'checkin']
2229
2966
 
2230
 
    def _get_bug_fix_properties(self, fixes, branch):
2231
 
        properties = []
 
2967
    def _iter_bug_fix_urls(self, fixes, branch):
2232
2968
        # Configure the properties for bug fixing attributes.
2233
2969
        for fixed_bug in fixes:
2234
2970
            tokens = fixed_bug.split(':')
2235
2971
            if len(tokens) != 2:
2236
2972
                raise errors.BzrCommandError(
2237
 
                    "Invalid bug %s. Must be in the form of 'tag:id'. "
2238
 
                    "Commit refused." % fixed_bug)
 
2973
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
 
2974
                    "See \"bzr help bugs\" for more information on this "
 
2975
                    "feature.\nCommit refused." % fixed_bug)
2239
2976
            tag, bug_id = tokens
2240
2977
            try:
2241
 
                bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
 
2978
                yield bugtracker.get_bug_url(tag, branch, bug_id)
2242
2979
            except errors.UnknownBugTrackerAbbreviation:
2243
2980
                raise errors.BzrCommandError(
2244
2981
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
2245
 
            except errors.MalformedBugIdentifier:
 
2982
            except errors.MalformedBugIdentifier, e:
2246
2983
                raise errors.BzrCommandError(
2247
 
                    "Invalid bug identifier for %s. Commit refused."
2248
 
                    % fixed_bug)
2249
 
            properties.append('%s fixed' % bug_url)
2250
 
        return '\n'.join(properties)
 
2984
                    "%s\nCommit refused." % (str(e),))
2251
2985
 
2252
2986
    def run(self, message=None, file=None, verbose=False, selected_list=None,
2253
2987
            unchanged=False, strict=False, local=False, fixes=None,
2254
 
            author=None, show_diff=False):
 
2988
            author=None, show_diff=False, exclude=None):
2255
2989
        from bzrlib.errors import (
2256
2990
            PointlessCommit,
2257
2991
            ConflictsInTree,
2259
2993
        )
2260
2994
        from bzrlib.msgeditor import (
2261
2995
            edit_commit_message_encoded,
 
2996
            generate_commit_message_template,
2262
2997
            make_commit_message_template_encoded
2263
2998
        )
2264
2999
 
2265
3000
        # TODO: Need a blackbox test for invoking the external editor; may be
2266
3001
        # slightly problematic to run this cross-platform.
2267
3002
 
2268
 
        # TODO: do more checks that the commit will succeed before 
 
3003
        # TODO: do more checks that the commit will succeed before
2269
3004
        # spending the user's valuable time typing a commit message.
2270
3005
 
2271
3006
        properties = {}
2279
3014
 
2280
3015
        if fixes is None:
2281
3016
            fixes = []
2282
 
        bug_property = self._get_bug_fix_properties(fixes, tree.branch)
 
3017
        bug_property = bugtracker.encode_fixes_bug_urls(
 
3018
            self._iter_bug_fix_urls(fixes, tree.branch))
2283
3019
        if bug_property:
2284
3020
            properties['bugs'] = bug_property
2285
3021
 
2292
3028
            if my_message is None and not file:
2293
3029
                t = make_commit_message_template_encoded(tree,
2294
3030
                        selected_list, diff=show_diff,
2295
 
                        output_encoding=bzrlib.user_encoding)
2296
 
                my_message = edit_commit_message_encoded(t)
 
3031
                        output_encoding=osutils.get_user_encoding())
 
3032
                start_message = generate_commit_message_template(commit_obj)
 
3033
                my_message = edit_commit_message_encoded(t,
 
3034
                    start_message=start_message)
2297
3035
                if my_message is None:
2298
3036
                    raise errors.BzrCommandError("please specify a commit"
2299
3037
                        " message with either --message or --file")
2301
3039
                raise errors.BzrCommandError(
2302
3040
                    "please specify either --message or --file")
2303
3041
            if file:
2304
 
                my_message = codecs.open(file, 'rt', 
2305
 
                                         bzrlib.user_encoding).read()
 
3042
                my_message = codecs.open(file, 'rt',
 
3043
                                         osutils.get_user_encoding()).read()
2306
3044
            if my_message == "":
2307
3045
                raise errors.BzrCommandError("empty commit message specified")
2308
3046
            return my_message
2309
3047
 
 
3048
        # The API permits a commit with a filter of [] to mean 'select nothing'
 
3049
        # but the command line should not do that.
 
3050
        if not selected_list:
 
3051
            selected_list = None
2310
3052
        try:
2311
3053
            tree.commit(message_callback=get_message,
2312
3054
                        specific_files=selected_list,
2313
3055
                        allow_pointless=unchanged, strict=strict, local=local,
2314
3056
                        reporter=None, verbose=verbose, revprops=properties,
2315
 
                        author=author)
 
3057
                        authors=author,
 
3058
                        exclude=safe_relpath_files(tree, exclude))
2316
3059
        except PointlessCommit:
2317
3060
            # FIXME: This should really happen before the file is read in;
2318
3061
            # perhaps prepare the commit; get the message; then actually commit
2319
 
            raise errors.BzrCommandError("no changes to commit."
2320
 
                              " use --unchanged to commit anyhow")
 
3062
            raise errors.BzrCommandError("No changes to commit."
 
3063
                              " Use --unchanged to commit anyhow.")
2321
3064
        except ConflictsInTree:
2322
3065
            raise errors.BzrCommandError('Conflicts detected in working '
2323
3066
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
2333
3076
 
2334
3077
 
2335
3078
class cmd_check(Command):
2336
 
    """Validate consistency of branch history.
2337
 
 
2338
 
    This command checks various invariants about the branch storage to
2339
 
    detect data corruption or bzr bugs.
2340
 
 
2341
 
    Output fields:
2342
 
 
2343
 
        revisions: This is just the number of revisions checked.  It doesn't
2344
 
            indicate a problem.
2345
 
        versionedfiles: This is just the number of versionedfiles checked.  It
2346
 
            doesn't indicate a problem.
2347
 
        unreferenced ancestors: Texts that are ancestors of other texts, but
2348
 
            are not properly referenced by the revision ancestry.  This is a
2349
 
            subtle problem that Bazaar can work around.
2350
 
        unique file texts: This is the total number of unique file contents
2351
 
            seen in the checked revisions.  It does not indicate a problem.
2352
 
        repeated file texts: This is the total number of repeated texts seen
2353
 
            in the checked revisions.  Texts can be repeated when their file
2354
 
            entries are modified, but the file contents are not.  It does not
2355
 
            indicate a problem.
 
3079
    """Validate working tree structure, branch consistency and repository history.
 
3080
 
 
3081
    This command checks various invariants about branch and repository storage
 
3082
    to detect data corruption or bzr bugs.
 
3083
 
 
3084
    The working tree and branch checks will only give output if a problem is
 
3085
    detected. The output fields of the repository check are:
 
3086
 
 
3087
    revisions
 
3088
        This is just the number of revisions checked.  It doesn't
 
3089
        indicate a problem.
 
3090
 
 
3091
    versionedfiles
 
3092
        This is just the number of versionedfiles checked.  It
 
3093
        doesn't indicate a problem.
 
3094
 
 
3095
    unreferenced ancestors
 
3096
        Texts that are ancestors of other texts, but
 
3097
        are not properly referenced by the revision ancestry.  This is a
 
3098
        subtle problem that Bazaar can work around.
 
3099
 
 
3100
    unique file texts
 
3101
        This is the total number of unique file contents
 
3102
        seen in the checked revisions.  It does not indicate a problem.
 
3103
 
 
3104
    repeated file texts
 
3105
        This is the total number of repeated texts seen
 
3106
        in the checked revisions.  Texts can be repeated when their file
 
3107
        entries are modified, but the file contents are not.  It does not
 
3108
        indicate a problem.
 
3109
 
 
3110
    If no restrictions are specified, all Bazaar data that is found at the given
 
3111
    location will be checked.
 
3112
 
 
3113
    :Examples:
 
3114
 
 
3115
        Check the tree and branch at 'foo'::
 
3116
 
 
3117
            bzr check --tree --branch foo
 
3118
 
 
3119
        Check only the repository at 'bar'::
 
3120
 
 
3121
            bzr check --repo bar
 
3122
 
 
3123
        Check everything at 'baz'::
 
3124
 
 
3125
            bzr check baz
2356
3126
    """
2357
3127
 
2358
3128
    _see_also = ['reconcile']
2359
 
    takes_args = ['branch?']
2360
 
    takes_options = ['verbose']
 
3129
    takes_args = ['path?']
 
3130
    takes_options = ['verbose',
 
3131
                     Option('branch', help="Check the branch related to the"
 
3132
                                           " current directory."),
 
3133
                     Option('repo', help="Check the repository related to the"
 
3134
                                         " current directory."),
 
3135
                     Option('tree', help="Check the working tree related to"
 
3136
                                         " the current directory.")]
2361
3137
 
2362
 
    def run(self, branch=None, verbose=False):
2363
 
        from bzrlib.check import check
2364
 
        if branch is None:
2365
 
            branch = Branch.open_containing('.')[0]
2366
 
        else:
2367
 
            branch = Branch.open(branch)
2368
 
        check(branch, verbose)
 
3138
    def run(self, path=None, verbose=False, branch=False, repo=False,
 
3139
            tree=False):
 
3140
        from bzrlib.check import check_dwim
 
3141
        if path is None:
 
3142
            path = '.'
 
3143
        if not branch and not repo and not tree:
 
3144
            branch = repo = tree = True
 
3145
        check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2369
3146
 
2370
3147
 
2371
3148
class cmd_upgrade(Command):
2382
3159
                    RegistryOption('format',
2383
3160
                        help='Upgrade to a specific format.  See "bzr help'
2384
3161
                             ' formats" for details.',
2385
 
                        registry=bzrdir.format_registry,
2386
 
                        converter=bzrdir.format_registry.make_bzrdir,
 
3162
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3163
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2387
3164
                        value_switches=True, title='Branch format'),
2388
3165
                    ]
2389
3166
 
2390
3167
    def run(self, url='.', format=None):
2391
3168
        from bzrlib.upgrade import upgrade
2392
 
        if format is None:
2393
 
            format = bzrdir.format_registry.make_bzrdir('default')
2394
3169
        upgrade(url, format)
2395
3170
 
2396
3171
 
2397
3172
class cmd_whoami(Command):
2398
3173
    """Show or set bzr user id.
2399
 
    
 
3174
 
2400
3175
    :Examples:
2401
3176
        Show the email of the current user::
2402
3177
 
2404
3179
 
2405
3180
        Set the current user::
2406
3181
 
2407
 
            bzr whoami 'Frank Chu <fchu@example.com>'
 
3182
            bzr whoami "Frank Chu <fchu@example.com>"
2408
3183
    """
2409
3184
    takes_options = [ Option('email',
2410
3185
                             help='Display email address only.'),
2414
3189
                    ]
2415
3190
    takes_args = ['name?']
2416
3191
    encoding_type = 'replace'
2417
 
    
 
3192
 
2418
3193
    @display_command
2419
3194
    def run(self, email=False, branch=False, name=None):
2420
3195
        if name is None:
2435
3210
        except errors.NoEmailInUsername, e:
2436
3211
            warning('"%s" does not seem to contain an email address.  '
2437
3212
                    'This is allowed, but not recommended.', name)
2438
 
        
 
3213
 
2439
3214
        # use global config unless --branch given
2440
3215
        if branch:
2441
3216
            c = Branch.open_containing('.')[0].get_config()
2445
3220
 
2446
3221
 
2447
3222
class cmd_nick(Command):
2448
 
    """Print or set the branch nickname.  
2449
 
 
2450
 
    If unset, the tree root directory name is used as the nickname
2451
 
    To print the current nickname, execute with no argument.  
 
3223
    """Print or set the branch nickname.
 
3224
 
 
3225
    If unset, the tree root directory name is used as the nickname.
 
3226
    To print the current nickname, execute with no argument.
 
3227
 
 
3228
    Bound branches use the nickname of its master branch unless it is set
 
3229
    locally.
2452
3230
    """
2453
3231
 
2454
3232
    _see_also = ['info']
2465
3243
        print branch.nick
2466
3244
 
2467
3245
 
 
3246
class cmd_alias(Command):
 
3247
    """Set/unset and display aliases.
 
3248
 
 
3249
    :Examples:
 
3250
        Show the current aliases::
 
3251
 
 
3252
            bzr alias
 
3253
 
 
3254
        Show the alias specified for 'll'::
 
3255
 
 
3256
            bzr alias ll
 
3257
 
 
3258
        Set an alias for 'll'::
 
3259
 
 
3260
            bzr alias ll="log --line -r-10..-1"
 
3261
 
 
3262
        To remove an alias for 'll'::
 
3263
 
 
3264
            bzr alias --remove ll
 
3265
 
 
3266
    """
 
3267
    takes_args = ['name?']
 
3268
    takes_options = [
 
3269
        Option('remove', help='Remove the alias.'),
 
3270
        ]
 
3271
 
 
3272
    def run(self, name=None, remove=False):
 
3273
        if remove:
 
3274
            self.remove_alias(name)
 
3275
        elif name is None:
 
3276
            self.print_aliases()
 
3277
        else:
 
3278
            equal_pos = name.find('=')
 
3279
            if equal_pos == -1:
 
3280
                self.print_alias(name)
 
3281
            else:
 
3282
                self.set_alias(name[:equal_pos], name[equal_pos+1:])
 
3283
 
 
3284
    def remove_alias(self, alias_name):
 
3285
        if alias_name is None:
 
3286
            raise errors.BzrCommandError(
 
3287
                'bzr alias --remove expects an alias to remove.')
 
3288
        # If alias is not found, print something like:
 
3289
        # unalias: foo: not found
 
3290
        c = config.GlobalConfig()
 
3291
        c.unset_alias(alias_name)
 
3292
 
 
3293
    @display_command
 
3294
    def print_aliases(self):
 
3295
        """Print out the defined aliases in a similar format to bash."""
 
3296
        aliases = config.GlobalConfig().get_aliases()
 
3297
        for key, value in sorted(aliases.iteritems()):
 
3298
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
 
3299
 
 
3300
    @display_command
 
3301
    def print_alias(self, alias_name):
 
3302
        from bzrlib.commands import get_alias
 
3303
        alias = get_alias(alias_name)
 
3304
        if alias is None:
 
3305
            self.outf.write("bzr alias: %s: not found\n" % alias_name)
 
3306
        else:
 
3307
            self.outf.write(
 
3308
                'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
 
3309
 
 
3310
    def set_alias(self, alias_name, alias_command):
 
3311
        """Save the alias in the global config."""
 
3312
        c = config.GlobalConfig()
 
3313
        c.set_alias(alias_name, alias_command)
 
3314
 
 
3315
 
2468
3316
class cmd_selftest(Command):
2469
3317
    """Run internal test suite.
2470
 
    
 
3318
 
2471
3319
    If arguments are given, they are regular expressions that say which tests
2472
3320
    should run.  Tests matching any expression are run, and other tests are
2473
3321
    not run.
2496
3344
    modified by plugins will not be tested, and tests provided by plugins will
2497
3345
    not be run.
2498
3346
 
2499
 
    Tests that need working space on disk use a common temporary directory, 
 
3347
    Tests that need working space on disk use a common temporary directory,
2500
3348
    typically inside $TMPDIR or /tmp.
2501
3349
 
2502
3350
    :Examples:
2550
3398
                            ),
2551
3399
                     Option('list-only',
2552
3400
                            help='List the tests instead of running them.'),
 
3401
                     RegistryOption('parallel',
 
3402
                        help="Run the test suite in parallel.",
 
3403
                        lazy_registry=('bzrlib.tests', 'parallel_registry'),
 
3404
                        value_switches=False,
 
3405
                        ),
2553
3406
                     Option('randomize', type=str, argname="SEED",
2554
3407
                            help='Randomize the order of tests using the given'
2555
3408
                                 ' seed or "now" for the current time.'),
2557
3410
                            short_name='x',
2558
3411
                            help='Exclude tests that match this regular'
2559
3412
                                 ' expression.'),
 
3413
                     Option('subunit',
 
3414
                        help='Output test progress via subunit.'),
2560
3415
                     Option('strict', help='Fail on missing dependencies or '
2561
3416
                            'known failures.'),
 
3417
                     Option('load-list', type=str, argname='TESTLISTFILE',
 
3418
                            help='Load a test id list from a text file.'),
 
3419
                     ListOption('debugflag', type=str, short_name='E',
 
3420
                                help='Turn on a selftest debug flag.'),
 
3421
                     ListOption('starting-with', type=str, argname='TESTID',
 
3422
                                param_name='starting_with', short_name='s',
 
3423
                                help=
 
3424
                                'Load only the tests starting with TESTID.'),
2562
3425
                     ]
2563
3426
    encoding_type = 'replace'
2564
3427
 
 
3428
    def __init__(self):
 
3429
        Command.__init__(self)
 
3430
        self.additional_selftest_args = {}
 
3431
 
2565
3432
    def run(self, testspecs_list=None, verbose=False, one=False,
2566
3433
            transport=None, benchmark=None,
2567
3434
            lsprof_timed=None, cache_dir=None,
2568
3435
            first=False, list_only=False,
2569
 
            randomize=None, exclude=None, strict=False):
2570
 
        import bzrlib.ui
 
3436
            randomize=None, exclude=None, strict=False,
 
3437
            load_list=None, debugflag=None, starting_with=None, subunit=False,
 
3438
            parallel=None):
2571
3439
        from bzrlib.tests import selftest
2572
3440
        import bzrlib.benchmarks as benchmarks
2573
3441
        from bzrlib.benchmarks import tree_creator
2574
3442
 
 
3443
        # Make deprecation warnings visible, unless -Werror is set
 
3444
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3445
 
2575
3446
        if cache_dir is not None:
2576
3447
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2577
 
        if not list_only:
2578
 
            print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2579
 
            print '   %s (%s python%s)' % (
2580
 
                    bzrlib.__path__[0],
2581
 
                    bzrlib.version_string,
2582
 
                    '.'.join(map(str, sys.version_info)),
2583
 
                    )
2584
 
        print
2585
3448
        if testspecs_list is not None:
2586
3449
            pattern = '|'.join(testspecs_list)
2587
3450
        else:
2588
3451
            pattern = ".*"
 
3452
        if subunit:
 
3453
            try:
 
3454
                from bzrlib.tests import SubUnitBzrRunner
 
3455
            except ImportError:
 
3456
                raise errors.BzrCommandError("subunit not available. subunit "
 
3457
                    "needs to be installed to use --subunit.")
 
3458
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
 
3459
        if parallel:
 
3460
            self.additional_selftest_args.setdefault(
 
3461
                'suite_decorators', []).append(parallel)
2589
3462
        if benchmark:
2590
3463
            test_suite_factory = benchmarks.test_suite
2591
3464
            # Unless user explicitly asks for quiet, be verbose in benchmarks
2596
3469
            test_suite_factory = None
2597
3470
            benchfile = None
2598
3471
        try:
2599
 
            result = selftest(verbose=verbose,
2600
 
                              pattern=pattern,
2601
 
                              stop_on_failure=one,
2602
 
                              transport=transport,
2603
 
                              test_suite_factory=test_suite_factory,
2604
 
                              lsprof_timed=lsprof_timed,
2605
 
                              bench_history=benchfile,
2606
 
                              matching_tests_first=first,
2607
 
                              list_only=list_only,
2608
 
                              random_seed=randomize,
2609
 
                              exclude_pattern=exclude,
2610
 
                              strict=strict,
2611
 
                              )
 
3472
            selftest_kwargs = {"verbose": verbose,
 
3473
                              "pattern": pattern,
 
3474
                              "stop_on_failure": one,
 
3475
                              "transport": transport,
 
3476
                              "test_suite_factory": test_suite_factory,
 
3477
                              "lsprof_timed": lsprof_timed,
 
3478
                              "bench_history": benchfile,
 
3479
                              "matching_tests_first": first,
 
3480
                              "list_only": list_only,
 
3481
                              "random_seed": randomize,
 
3482
                              "exclude_pattern": exclude,
 
3483
                              "strict": strict,
 
3484
                              "load_list": load_list,
 
3485
                              "debug_flags": debugflag,
 
3486
                              "starting_with": starting_with
 
3487
                              }
 
3488
            selftest_kwargs.update(self.additional_selftest_args)
 
3489
            result = selftest(**selftest_kwargs)
2612
3490
        finally:
2613
3491
            if benchfile is not None:
2614
3492
                benchfile.close()
2615
 
        if result:
2616
 
            info('tests passed')
2617
 
        else:
2618
 
            info('tests failed')
2619
3493
        return int(not result)
2620
3494
 
2621
3495
 
2623
3497
    """Show version of bzr."""
2624
3498
 
2625
3499
    encoding_type = 'replace'
 
3500
    takes_options = [
 
3501
        Option("short", help="Print just the version number."),
 
3502
        ]
2626
3503
 
2627
3504
    @display_command
2628
 
    def run(self):
 
3505
    def run(self, short=False):
2629
3506
        from bzrlib.version import show_version
2630
 
        show_version(to_file=self.outf)
 
3507
        if short:
 
3508
            self.outf.write(bzrlib.version_string + '\n')
 
3509
        else:
 
3510
            show_version(to_file=self.outf)
2631
3511
 
2632
3512
 
2633
3513
class cmd_rocks(Command):
2646
3526
    #       merging only part of the history.
2647
3527
    takes_args = ['branch', 'other']
2648
3528
    hidden = True
2649
 
    
 
3529
 
2650
3530
    @display_command
2651
3531
    def run(self, branch, other):
2652
3532
        from bzrlib.revision import ensure_null
2653
 
        
 
3533
 
2654
3534
        branch1 = Branch.open_containing(branch)[0]
2655
3535
        branch2 = Branch.open_containing(other)[0]
2656
 
 
2657
 
        last1 = ensure_null(branch1.last_revision())
2658
 
        last2 = ensure_null(branch2.last_revision())
2659
 
 
2660
 
        graph = branch1.repository.get_graph(branch2.repository)
2661
 
        base_rev_id = graph.find_unique_lca(last1, last2)
2662
 
 
2663
 
        print 'merge base is revision %s' % base_rev_id
 
3536
        branch1.lock_read()
 
3537
        try:
 
3538
            branch2.lock_read()
 
3539
            try:
 
3540
                last1 = ensure_null(branch1.last_revision())
 
3541
                last2 = ensure_null(branch2.last_revision())
 
3542
 
 
3543
                graph = branch1.repository.get_graph(branch2.repository)
 
3544
                base_rev_id = graph.find_unique_lca(last1, last2)
 
3545
 
 
3546
                print 'merge base is revision %s' % base_rev_id
 
3547
            finally:
 
3548
                branch2.unlock()
 
3549
        finally:
 
3550
            branch1.unlock()
2664
3551
 
2665
3552
 
2666
3553
class cmd_merge(Command):
2667
3554
    """Perform a three-way merge.
2668
 
    
2669
 
    The branch is the branch you will merge from.  By default, it will merge
2670
 
    the latest revision.  If you specify a revision, that revision will be
2671
 
    merged.  If you specify two revisions, the first will be used as a BASE,
2672
 
    and the second one as OTHER.  Revision numbers are always relative to the
2673
 
    specified branch.
 
3555
 
 
3556
    The source of the merge can be specified either in the form of a branch,
 
3557
    or in the form of a path to a file containing a merge directive generated
 
3558
    with bzr send. If neither is specified, the default is the upstream branch
 
3559
    or the branch most recently merged using --remember.
 
3560
 
 
3561
    When merging a branch, by default the tip will be merged. To pick a different
 
3562
    revision, pass --revision. If you specify two values, the first will be used as
 
3563
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
3564
    available revisions, like this is commonly referred to as "cherrypicking".
 
3565
 
 
3566
    Revision numbers are always relative to the branch being merged.
2674
3567
 
2675
3568
    By default, bzr will try to merge in all new work from the other
2676
3569
    branch, automatically determining an appropriate base.  If this
2677
3570
    fails, you may need to give an explicit base.
2678
 
    
 
3571
 
2679
3572
    Merge will do its best to combine the changes in two branches, but there
2680
3573
    are some kinds of problems only a human can fix.  When it encounters those,
2681
3574
    it will mark a conflict.  A conflict means that you need to fix something,
2691
3584
    The results of the merge are placed into the destination working
2692
3585
    directory, where they can be reviewed (with bzr diff), tested, and then
2693
3586
    committed to record the result of the merge.
2694
 
    
 
3587
 
2695
3588
    merge refuses to run if there are any uncommitted changes, unless
2696
3589
    --force is given.
2697
3590
 
 
3591
    To select only some changes to merge, use "merge -i", which will prompt
 
3592
    you to apply each diff hunk and file change, similar to "shelve".
 
3593
 
2698
3594
    :Examples:
2699
3595
        To merge the latest revision from bzr.dev::
2700
3596
 
2707
3603
        To merge the changes introduced by 82, without previous changes::
2708
3604
 
2709
3605
            bzr merge -r 81..82 ../bzr.dev
 
3606
 
 
3607
        To apply a merge directive contained in /tmp/merge:
 
3608
 
 
3609
            bzr merge /tmp/merge
2710
3610
    """
2711
3611
 
2712
 
    _see_also = ['update', 'remerge', 'status-flags']
2713
 
    takes_args = ['branch?']
 
3612
    encoding_type = 'exact'
 
3613
    _see_also = ['update', 'remerge', 'status-flags', 'send']
 
3614
    takes_args = ['location?']
2714
3615
    takes_options = [
2715
3616
        'change',
2716
3617
        'revision',
2733
3634
               short_name='d',
2734
3635
               type=unicode,
2735
3636
               ),
 
3637
        Option('preview', help='Instead of merging, show a diff of the'
 
3638
               ' merge.'),
 
3639
        Option('interactive', help='Select changes interactively.',
 
3640
            short_name='i')
2736
3641
    ]
2737
3642
 
2738
 
    def run(self, branch=None, revision=None, force=False, merge_type=None,
2739
 
            show_base=False, reprocess=False, remember=False,
 
3643
    def run(self, location=None, revision=None, force=False,
 
3644
            merge_type=None, show_base=False, reprocess=None, remember=False,
2740
3645
            uncommitted=False, pull=False,
2741
3646
            directory=None,
 
3647
            preview=False,
 
3648
            interactive=False,
2742
3649
            ):
2743
 
        # This is actually a branch (or merge-directive) *location*.
2744
 
        location = branch
2745
 
        del branch
2746
 
 
2747
3650
        if merge_type is None:
2748
3651
            merge_type = _mod_merge.Merge3Merger
2749
3652
 
2753
3656
        allow_pending = True
2754
3657
        verified = 'inapplicable'
2755
3658
        tree = WorkingTree.open_containing(directory)[0]
 
3659
 
 
3660
        # die as quickly as possible if there are uncommitted changes
 
3661
        try:
 
3662
            basis_tree = tree.revision_tree(tree.last_revision())
 
3663
        except errors.NoSuchRevision:
 
3664
            basis_tree = tree.basis_tree()
 
3665
        if not force:
 
3666
            if tree.has_changes(basis_tree):
 
3667
                raise errors.UncommittedChanges(tree)
 
3668
 
 
3669
        view_info = _get_view_info_for_change_reporter(tree)
2756
3670
        change_reporter = delta._ChangeReporter(
2757
 
            unversioned_filter=tree.is_ignored)
 
3671
            unversioned_filter=tree.is_ignored, view_info=view_info)
2758
3672
        cleanups = []
2759
3673
        try:
2760
3674
            pb = ui.ui_factory.nested_progress_bar()
2762
3676
            tree.lock_write()
2763
3677
            cleanups.append(tree.unlock)
2764
3678
            if location is not None:
2765
 
                mergeable, other_transport = _get_mergeable_helper(location)
2766
 
                if mergeable:
 
3679
                try:
 
3680
                    mergeable = bundle.read_mergeable_from_url(location,
 
3681
                        possible_transports=possible_transports)
 
3682
                except errors.NotABundle:
 
3683
                    mergeable = None
 
3684
                else:
2767
3685
                    if uncommitted:
2768
3686
                        raise errors.BzrCommandError('Cannot use --uncommitted'
2769
3687
                            ' with bundles or merge directives.')
2773
3691
                            'Cannot use -r with merge directives or bundles')
2774
3692
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
2775
3693
                       mergeable, pb)
2776
 
                possible_transports.append(other_transport)
2777
3694
 
2778
3695
            if merger is None and uncommitted:
2779
3696
                if revision is not None and len(revision) > 0:
2780
3697
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
2781
3698
                        ' --revision at the same time.')
2782
 
                location = self._select_branch_location(tree, location)[0]
2783
 
                other_tree, other_path = WorkingTree.open_containing(location)
2784
 
                merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2785
 
                    pb)
 
3699
                merger = self.get_merger_from_uncommitted(tree, location, pb,
 
3700
                                                          cleanups)
2786
3701
                allow_pending = False
2787
3702
 
2788
3703
            if merger is None:
2792
3707
            merger.merge_type = merge_type
2793
3708
            merger.reprocess = reprocess
2794
3709
            merger.show_base = show_base
2795
 
            merger.change_reporter = change_reporter
2796
3710
            self.sanity_check_merger(merger)
2797
3711
            if (merger.base_rev_id == merger.other_rev_id and
2798
 
                merger.other_rev_id != None):
 
3712
                merger.other_rev_id is not None):
2799
3713
                note('Nothing to do.')
2800
3714
                return 0
2801
3715
            if pull:
2806
3720
                                       merger.other_rev_id)
2807
3721
                    result.report(self.outf)
2808
3722
                    return 0
2809
 
            merger.check_basis(not force)
2810
 
            conflict_count = merger.do_merge()
2811
 
            if allow_pending:
2812
 
                merger.set_pending()
2813
 
            if verified == 'failed':
2814
 
                warning('Preview patch does not match changes')
2815
 
            if conflict_count != 0:
2816
 
                return 1
 
3723
            merger.check_basis(False)
 
3724
            if preview:
 
3725
                return self._do_preview(merger, cleanups)
 
3726
            elif interactive:
 
3727
                return self._do_interactive(merger, cleanups)
2817
3728
            else:
2818
 
                return 0
 
3729
                return self._do_merge(merger, change_reporter, allow_pending,
 
3730
                                      verified)
2819
3731
        finally:
2820
3732
            for cleanup in reversed(cleanups):
2821
3733
                cleanup()
2822
3734
 
 
3735
    def _get_preview(self, merger, cleanups):
 
3736
        tree_merger = merger.make_merger()
 
3737
        tt = tree_merger.make_preview_transform()
 
3738
        cleanups.append(tt.finalize)
 
3739
        result_tree = tt.get_preview_tree()
 
3740
        return result_tree
 
3741
 
 
3742
    def _do_preview(self, merger, cleanups):
 
3743
        from bzrlib.diff import show_diff_trees
 
3744
        result_tree = self._get_preview(merger, cleanups)
 
3745
        show_diff_trees(merger.this_tree, result_tree, self.outf,
 
3746
                        old_label='', new_label='')
 
3747
 
 
3748
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
 
3749
        merger.change_reporter = change_reporter
 
3750
        conflict_count = merger.do_merge()
 
3751
        if allow_pending:
 
3752
            merger.set_pending()
 
3753
        if verified == 'failed':
 
3754
            warning('Preview patch does not match changes')
 
3755
        if conflict_count != 0:
 
3756
            return 1
 
3757
        else:
 
3758
            return 0
 
3759
 
 
3760
    def _do_interactive(self, merger, cleanups):
 
3761
        """Perform an interactive merge.
 
3762
 
 
3763
        This works by generating a preview tree of the merge, then using
 
3764
        Shelver to selectively remove the differences between the working tree
 
3765
        and the preview tree.
 
3766
        """
 
3767
        from bzrlib import shelf_ui
 
3768
        result_tree = self._get_preview(merger, cleanups)
 
3769
        writer = bzrlib.option.diff_writer_registry.get()
 
3770
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
 
3771
                                   reporter=shelf_ui.ApplyReporter(),
 
3772
                                   diff_writer=writer(sys.stdout))
 
3773
        shelver.run()
 
3774
 
2823
3775
    def sanity_check_merger(self, merger):
2824
3776
        if (merger.show_base and
2825
3777
            not merger.merge_type is _mod_merge.Merge3Merger):
2826
3778
            raise errors.BzrCommandError("Show-base is not supported for this"
2827
3779
                                         " merge type. %s" % merger.merge_type)
 
3780
        if merger.reprocess is None:
 
3781
            if merger.show_base:
 
3782
                merger.reprocess = False
 
3783
            else:
 
3784
                # Use reprocess if the merger supports it
 
3785
                merger.reprocess = merger.merge_type.supports_reprocess
2828
3786
        if merger.reprocess and not merger.merge_type.supports_reprocess:
2829
3787
            raise errors.BzrCommandError("Conflict reduction is not supported"
2830
3788
                                         " for merge type %s." %
2837
3795
                                possible_transports, pb):
2838
3796
        """Produce a merger from a location, assuming it refers to a branch."""
2839
3797
        from bzrlib.tag import _merge_tags_if_possible
2840
 
        assert revision is None or len(revision) < 3
2841
3798
        # find the branch locations
2842
 
        other_loc, location = self._select_branch_location(tree, location,
 
3799
        other_loc, user_location = self._select_branch_location(tree, location,
2843
3800
            revision, -1)
2844
3801
        if revision is not None and len(revision) == 2:
2845
 
            base_loc, location = self._select_branch_location(tree, location,
2846
 
                                                              revision, 0)
 
3802
            base_loc, _unused = self._select_branch_location(tree,
 
3803
                location, revision, 0)
2847
3804
        else:
2848
3805
            base_loc = other_loc
2849
3806
        # Open the branches
2855
3812
            base_branch, base_path = Branch.open_containing(base_loc,
2856
3813
                possible_transports)
2857
3814
        # Find the revision ids
2858
 
        if revision is None or len(revision) < 1 or revision[-1] is None:
 
3815
        other_revision_id = None
 
3816
        base_revision_id = None
 
3817
        if revision is not None:
 
3818
            if len(revision) >= 1:
 
3819
                other_revision_id = revision[-1].as_revision_id(other_branch)
 
3820
            if len(revision) == 2:
 
3821
                base_revision_id = revision[0].as_revision_id(base_branch)
 
3822
        if other_revision_id is None:
2859
3823
            other_revision_id = _mod_revision.ensure_null(
2860
3824
                other_branch.last_revision())
2861
 
        else:
2862
 
            other_revision_id = \
2863
 
                _mod_revision.ensure_null(
2864
 
                    revision[-1].in_history(other_branch).rev_id)
2865
 
        if (revision is not None and len(revision) == 2
2866
 
            and revision[0] is not None):
2867
 
            base_revision_id = \
2868
 
                _mod_revision.ensure_null(
2869
 
                    revision[0].in_history(base_branch).rev_id)
2870
 
        else:
2871
 
            base_revision_id = None
2872
3825
        # Remember where we merge from
2873
 
        if ((tree.branch.get_parent() is None or remember) and
2874
 
            other_branch is not None):
2875
 
            tree.branch.set_parent(other_branch.base)
 
3826
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3827
             user_location is not None):
 
3828
            tree.branch.set_submit_branch(other_branch.base)
2876
3829
        _merge_tags_if_possible(other_branch, tree.branch)
2877
3830
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
2878
3831
            other_revision_id, base_revision_id, other_branch, base_branch)
2883
3836
            allow_pending = True
2884
3837
        return merger, allow_pending
2885
3838
 
2886
 
    def _select_branch_location(self, tree, location, revision=None,
 
3839
    def get_merger_from_uncommitted(self, tree, location, pb, cleanups):
 
3840
        """Get a merger for uncommitted changes.
 
3841
 
 
3842
        :param tree: The tree the merger should apply to.
 
3843
        :param location: The location containing uncommitted changes.
 
3844
        :param pb: The progress bar to use for showing progress.
 
3845
        :param cleanups: A list of operations to perform to clean up the
 
3846
            temporary directories, unfinalized objects, etc.
 
3847
        """
 
3848
        location = self._select_branch_location(tree, location)[0]
 
3849
        other_tree, other_path = WorkingTree.open_containing(location)
 
3850
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
 
3851
        if other_path != '':
 
3852
            merger.interesting_files = [other_path]
 
3853
        return merger
 
3854
 
 
3855
    def _select_branch_location(self, tree, user_location, revision=None,
2887
3856
                                index=None):
2888
3857
        """Select a branch location, according to possible inputs.
2889
3858
 
2891
3860
        ``revision`` and ``index`` must be supplied.)
2892
3861
 
2893
3862
        Otherwise, the ``location`` parameter is used.  If it is None, then the
2894
 
        ``parent`` location is used, and a note is printed.
 
3863
        ``submit`` or ``parent`` location is used, and a note is printed.
2895
3864
 
2896
3865
        :param tree: The working tree to select a branch for merging into
2897
3866
        :param location: The location entered by the user
2898
3867
        :param revision: The revision parameter to the command
2899
3868
        :param index: The index to use for the revision parameter.  Negative
2900
3869
            indices are permitted.
2901
 
        :return: (selected_location, default_location).  The default location
2902
 
            will be the user-entered location, if any, or else the remembered
2903
 
            location.
 
3870
        :return: (selected_location, user_location).  The default location
 
3871
            will be the user-entered location.
2904
3872
        """
2905
3873
        if (revision is not None and index is not None
2906
3874
            and revision[index] is not None):
2907
3875
            branch = revision[index].get_branch()
2908
3876
            if branch is not None:
2909
 
                return branch, location
2910
 
        location = self._get_remembered_parent(tree, location, 'Merging from')
2911
 
        return location, location
 
3877
                return branch, branch
 
3878
        if user_location is None:
 
3879
            location = self._get_remembered(tree, 'Merging from')
 
3880
        else:
 
3881
            location = user_location
 
3882
        return location, user_location
2912
3883
 
2913
 
    # TODO: move up to common parent; this isn't merge-specific anymore. 
2914
 
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
 
3884
    def _get_remembered(self, tree, verb_string):
2915
3885
        """Use tree.branch's parent if none was supplied.
2916
3886
 
2917
3887
        Report if the remembered location was used.
2918
3888
        """
2919
 
        if supplied_location is not None:
2920
 
            return supplied_location
2921
 
        stored_location = tree.branch.get_parent()
 
3889
        stored_location = tree.branch.get_submit_branch()
 
3890
        stored_location_type = "submit"
 
3891
        if stored_location is None:
 
3892
            stored_location = tree.branch.get_parent()
 
3893
            stored_location_type = "parent"
2922
3894
        mutter("%s", stored_location)
2923
3895
        if stored_location is None:
2924
3896
            raise errors.BzrCommandError("No location specified or remembered")
2925
 
        display_url = urlutils.unescape_for_display(stored_location,
2926
 
            self.outf.encoding)
2927
 
        self.outf.write("%s remembered location %s\n" % (verb_string,
2928
 
            display_url))
 
3897
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
 
3898
        note(u"%s remembered %s location %s", verb_string,
 
3899
                stored_location_type, display_url)
2929
3900
        return stored_location
2930
3901
 
2931
3902
 
2933
3904
    """Redo a merge.
2934
3905
 
2935
3906
    Use this if you want to try a different merge technique while resolving
2936
 
    conflicts.  Some merge techniques are better than others, and remerge 
 
3907
    conflicts.  Some merge techniques are better than others, and remerge
2937
3908
    lets you try different ones on different files.
2938
3909
 
2939
3910
    The options for remerge have the same meaning and defaults as the ones for
2943
3914
    :Examples:
2944
3915
        Re-do the merge of all conflicted files, and show the base text in
2945
3916
        conflict regions, in addition to the usual THIS and OTHER texts::
2946
 
      
 
3917
 
2947
3918
            bzr remerge --show-base
2948
3919
 
2949
3920
        Re-do the merge of "foobar", using the weave merge algorithm, with
2950
3921
        additional processing to reduce the size of conflict regions::
2951
 
      
 
3922
 
2952
3923
            bzr remerge --merge-type weave --reprocess foobar
2953
3924
    """
2954
3925
    takes_args = ['file*']
2972
3943
                                             " merges.  Not cherrypicking or"
2973
3944
                                             " multi-merges.")
2974
3945
            repository = tree.branch.repository
2975
 
            graph = repository.get_graph()
2976
 
            base_revision = graph.find_unique_lca(parents[0], parents[1])
2977
 
            base_tree = repository.revision_tree(base_revision)
2978
 
            other_tree = repository.revision_tree(parents[1])
2979
3946
            interesting_ids = None
2980
3947
            new_conflicts = []
2981
3948
            conflicts = tree.conflicts()
2988
3955
                    interesting_ids.add(file_id)
2989
3956
                    if tree.kind(file_id) != "directory":
2990
3957
                        continue
2991
 
                    
 
3958
 
2992
3959
                    for name, ie in tree.inventory.iter_entries(file_id):
2993
3960
                        interesting_ids.add(ie.file_id)
2994
3961
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3011
3978
            # list, we imply that the working tree text has seen and rejected
3012
3979
            # all the changes from the other tree, when in fact those changes
3013
3980
            # have not yet been seen.
 
3981
            pb = ui.ui_factory.nested_progress_bar()
3014
3982
            tree.set_parent_ids(parents[:1])
3015
3983
            try:
3016
 
                conflicts = _mod_merge.merge_inner(
3017
 
                                          tree.branch, other_tree, base_tree,
3018
 
                                          this_tree=tree,
3019
 
                                          interesting_ids=interesting_ids,
3020
 
                                          other_rev_id=parents[1],
3021
 
                                          merge_type=merge_type,
3022
 
                                          show_base=show_base,
3023
 
                                          reprocess=reprocess)
 
3984
                merger = _mod_merge.Merger.from_revision_ids(pb,
 
3985
                                                             tree, parents[1])
 
3986
                merger.interesting_ids = interesting_ids
 
3987
                merger.merge_type = merge_type
 
3988
                merger.show_base = show_base
 
3989
                merger.reprocess = reprocess
 
3990
                conflicts = merger.do_merge()
3024
3991
            finally:
3025
3992
                tree.set_parent_ids(parents)
 
3993
                pb.finished()
3026
3994
        finally:
3027
3995
            tree.unlock()
3028
3996
        if conflicts > 0:
3039
4007
    last committed revision is used.
3040
4008
 
3041
4009
    To remove only some changes, without reverting to a prior version, use
3042
 
    merge instead.  For example, "merge . --r-2..-3" will remove the changes
3043
 
    introduced by -2, without affecting the changes introduced by -1.  Or
3044
 
    to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3045
 
    
 
4010
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
4011
    changes introduced by -2, without affecting the changes introduced by -1.
 
4012
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
 
4013
 
3046
4014
    By default, any files that have been manually changed will be backed up
3047
4015
    first.  (Files changed only by merge are not backed up.)  Backup files have
3048
4016
    '.~#~' appended to their name, where # is a number.
3058
4026
 
3059
4027
    The working tree contains a list of pending merged revisions, which will
3060
4028
    be included as parents in the next commit.  Normally, revert clears that
3061
 
    list as well as reverting the files.  If any files, are specified, revert
3062
 
    leaves the pending merge list alnone and reverts only the files.  Use "bzr
 
4029
    list as well as reverting the files.  If any files are specified, revert
 
4030
    leaves the pending merge list alone and reverts only the files.  Use "bzr
3063
4031
    revert ." in the tree root to revert all files but keep the merge record,
3064
4032
    and "bzr revert --forget-merges" to clear the pending merge list without
3065
4033
    reverting any files.
3077
4045
    def run(self, revision=None, no_backup=False, file_list=None,
3078
4046
            forget_merges=None):
3079
4047
        tree, file_list = tree_files(file_list)
3080
 
        if forget_merges:
3081
 
            tree.set_parent_ids(tree.get_parent_ids()[:1])
3082
 
        else:
3083
 
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4048
        tree.lock_write()
 
4049
        try:
 
4050
            if forget_merges:
 
4051
                tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4052
            else:
 
4053
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4054
        finally:
 
4055
            tree.unlock()
3084
4056
 
3085
4057
    @staticmethod
3086
4058
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3087
 
        if revision is None:
3088
 
            rev_id = tree.last_revision()
3089
 
        elif len(revision) != 1:
3090
 
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
3091
 
        else:
3092
 
            rev_id = revision[0].in_history(tree.branch).rev_id
 
4059
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3093
4060
        pb = ui.ui_factory.nested_progress_bar()
3094
4061
        try:
3095
 
            tree.revert(file_list,
3096
 
                        tree.branch.repository.revision_tree(rev_id),
3097
 
                        not no_backup, pb, report_changes=True)
 
4062
            tree.revert(file_list, rev_tree, not no_backup, pb,
 
4063
                report_changes=True)
3098
4064
        finally:
3099
4065
            pb.finished()
3100
4066
 
3119
4085
            ]
3120
4086
    takes_args = ['topic?']
3121
4087
    aliases = ['?', '--help', '-?', '-h']
3122
 
    
 
4088
 
3123
4089
    @display_command
3124
4090
    def run(self, topic=None, long=False):
3125
4091
        import bzrlib.help
3136
4102
    takes_args = ['context?']
3137
4103
    aliases = ['s-c']
3138
4104
    hidden = True
3139
 
    
 
4105
 
3140
4106
    @display_command
3141
4107
    def run(self, context=None):
3142
4108
        import shellcomplete
3143
4109
        shellcomplete.shellcomplete(context)
3144
4110
 
3145
4111
 
3146
 
class cmd_fetch(Command):
3147
 
    """Copy in history from another branch but don't merge it.
3148
 
 
3149
 
    This is an internal method used for pull and merge.
3150
 
    """
3151
 
    hidden = True
3152
 
    takes_args = ['from_branch', 'to_branch']
3153
 
    def run(self, from_branch, to_branch):
3154
 
        from bzrlib.fetch import Fetcher
3155
 
        from_b = Branch.open(from_branch)
3156
 
        to_b = Branch.open(to_branch)
3157
 
        Fetcher(to_b, from_b)
3158
 
 
3159
 
 
3160
4112
class cmd_missing(Command):
3161
4113
    """Show unmerged/unpulled revisions between two branches.
3162
 
    
 
4114
 
3163
4115
    OTHER_BRANCH may be local or remote.
 
4116
 
 
4117
    To filter on a range of revisions, you can use the command -r begin..end
 
4118
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
4119
    also valid.
 
4120
 
 
4121
    :Examples:
 
4122
 
 
4123
        Determine the missing revisions between this and the branch at the
 
4124
        remembered pull location::
 
4125
 
 
4126
            bzr missing
 
4127
 
 
4128
        Determine the missing revisions between this and another branch::
 
4129
 
 
4130
            bzr missing http://server/branch
 
4131
 
 
4132
        Determine the missing revisions up to a specific revision on the other
 
4133
        branch::
 
4134
 
 
4135
            bzr missing -r ..-10
 
4136
 
 
4137
        Determine the missing revisions up to a specific revision on this
 
4138
        branch::
 
4139
 
 
4140
            bzr missing --my-revision ..-10
3164
4141
    """
3165
4142
 
3166
4143
    _see_also = ['merge', 'pull']
3167
4144
    takes_args = ['other_branch?']
3168
4145
    takes_options = [
3169
 
            Option('reverse', 'Reverse the order of revisions.'),
3170
 
            Option('mine-only',
3171
 
                   'Display changes in the local branch only.'),
3172
 
            Option('this' , 'Same as --mine-only.'),
3173
 
            Option('theirs-only',
3174
 
                   'Display changes in the remote branch only.'),
3175
 
            Option('other', 'Same as --theirs-only.'),
3176
 
            'log-format',
3177
 
            'show-ids',
3178
 
            'verbose'
3179
 
            ]
 
4146
        Option('reverse', 'Reverse the order of revisions.'),
 
4147
        Option('mine-only',
 
4148
               'Display changes in the local branch only.'),
 
4149
        Option('this' , 'Same as --mine-only.'),
 
4150
        Option('theirs-only',
 
4151
               'Display changes in the remote branch only.'),
 
4152
        Option('other', 'Same as --theirs-only.'),
 
4153
        'log-format',
 
4154
        'show-ids',
 
4155
        'verbose',
 
4156
        custom_help('revision',
 
4157
             help='Filter on other branch revisions (inclusive). '
 
4158
                'See "help revisionspec" for details.'),
 
4159
        Option('my-revision',
 
4160
            type=_parse_revision_str,
 
4161
            help='Filter on local branch revisions (inclusive). '
 
4162
                'See "help revisionspec" for details.'),
 
4163
        Option('include-merges',
 
4164
               'Show all revisions in addition to the mainline ones.'),
 
4165
        ]
3180
4166
    encoding_type = 'replace'
3181
4167
 
3182
4168
    @display_command
3183
4169
    def run(self, other_branch=None, reverse=False, mine_only=False,
3184
 
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
3185
 
            show_ids=False, verbose=False, this=False, other=False):
 
4170
            theirs_only=False,
 
4171
            log_format=None, long=False, short=False, line=False,
 
4172
            show_ids=False, verbose=False, this=False, other=False,
 
4173
            include_merges=False, revision=None, my_revision=None):
3186
4174
        from bzrlib.missing import find_unmerged, iter_log_revisions
 
4175
        def message(s):
 
4176
            if not is_quiet():
 
4177
                self.outf.write(s)
3187
4178
 
3188
4179
        if this:
3189
 
          mine_only = this
 
4180
            mine_only = this
3190
4181
        if other:
3191
 
          theirs_only = other
 
4182
            theirs_only = other
 
4183
        # TODO: We should probably check that we don't have mine-only and
 
4184
        #       theirs-only set, but it gets complicated because we also have
 
4185
        #       this and other which could be used.
 
4186
        restrict = 'all'
 
4187
        if mine_only:
 
4188
            restrict = 'local'
 
4189
        elif theirs_only:
 
4190
            restrict = 'remote'
3192
4191
 
3193
4192
        local_branch = Branch.open_containing(u".")[0]
3194
4193
        parent = local_branch.get_parent()
3199
4198
                                             " or specified.")
3200
4199
            display_url = urlutils.unescape_for_display(parent,
3201
4200
                                                        self.outf.encoding)
3202
 
            self.outf.write("Using last location: " + display_url + "\n")
 
4201
            message("Using saved parent location: "
 
4202
                    + display_url + "\n")
3203
4203
 
3204
4204
        remote_branch = Branch.open(other_branch)
3205
4205
        if remote_branch.base == local_branch.base:
3206
4206
            remote_branch = local_branch
 
4207
 
 
4208
        local_revid_range = _revision_range_to_revid_range(
 
4209
            _get_revision_range(my_revision, local_branch,
 
4210
                self.name()))
 
4211
 
 
4212
        remote_revid_range = _revision_range_to_revid_range(
 
4213
            _get_revision_range(revision,
 
4214
                remote_branch, self.name()))
 
4215
 
3207
4216
        local_branch.lock_read()
3208
4217
        try:
3209
4218
            remote_branch.lock_read()
3210
4219
            try:
3211
 
                local_extra, remote_extra = find_unmerged(local_branch,
3212
 
                                                          remote_branch)
 
4220
                local_extra, remote_extra = find_unmerged(
 
4221
                    local_branch, remote_branch, restrict,
 
4222
                    backward=not reverse,
 
4223
                    include_merges=include_merges,
 
4224
                    local_revid_range=local_revid_range,
 
4225
                    remote_revid_range=remote_revid_range)
 
4226
 
3213
4227
                if log_format is None:
3214
4228
                    registry = log.log_formatter_registry
3215
4229
                    log_format = registry.get_default(local_branch)
3216
4230
                lf = log_format(to_file=self.outf,
3217
4231
                                show_ids=show_ids,
3218
4232
                                show_timezone='original')
3219
 
                if reverse is False:
3220
 
                    local_extra.reverse()
3221
 
                    remote_extra.reverse()
 
4233
 
 
4234
                status_code = 0
3222
4235
                if local_extra and not theirs_only:
3223
 
                    self.outf.write("You have %d extra revision(s):\n" %
3224
 
                                    len(local_extra))
 
4236
                    message("You have %d extra revision(s):\n" %
 
4237
                        len(local_extra))
3225
4238
                    for revision in iter_log_revisions(local_extra,
3226
4239
                                        local_branch.repository,
3227
4240
                                        verbose):
3228
4241
                        lf.log_revision(revision)
3229
4242
                    printed_local = True
 
4243
                    status_code = 1
3230
4244
                else:
3231
4245
                    printed_local = False
 
4246
 
3232
4247
                if remote_extra and not mine_only:
3233
4248
                    if printed_local is True:
3234
 
                        self.outf.write("\n\n\n")
3235
 
                    self.outf.write("You are missing %d revision(s):\n" %
3236
 
                                    len(remote_extra))
 
4249
                        message("\n\n\n")
 
4250
                    message("You are missing %d revision(s):\n" %
 
4251
                        len(remote_extra))
3237
4252
                    for revision in iter_log_revisions(remote_extra,
3238
4253
                                        remote_branch.repository,
3239
4254
                                        verbose):
3240
4255
                        lf.log_revision(revision)
3241
 
                if not remote_extra and not local_extra:
3242
 
                    status_code = 0
3243
 
                    self.outf.write("Branches are up to date.\n")
3244
 
                else:
3245
4256
                    status_code = 1
 
4257
 
 
4258
                if mine_only and not local_extra:
 
4259
                    # We checked local, and found nothing extra
 
4260
                    message('This branch is up to date.\n')
 
4261
                elif theirs_only and not remote_extra:
 
4262
                    # We checked remote, and found nothing extra
 
4263
                    message('Other branch is up to date.\n')
 
4264
                elif not (mine_only or theirs_only or local_extra or
 
4265
                          remote_extra):
 
4266
                    # We checked both branches, and neither one had extra
 
4267
                    # revisions
 
4268
                    message("Branches are up to date.\n")
3246
4269
            finally:
3247
4270
                remote_branch.unlock()
3248
4271
        finally:
3276
4299
 
3277
4300
class cmd_plugins(Command):
3278
4301
    """List the installed plugins.
3279
 
    
3280
 
    This command displays the list of installed plugins including the
3281
 
    path where each one is located and a short description of each.
 
4302
 
 
4303
    This command displays the list of installed plugins including
 
4304
    version of plugin and a short description of each.
 
4305
 
 
4306
    --verbose shows the path where each plugin is located.
3282
4307
 
3283
4308
    A plugin is an external component for Bazaar that extends the
3284
4309
    revision control system, by adding or replacing code in Bazaar.
3291
4316
    install them. Instructions are also provided there on how to
3292
4317
    write new plugins using the Python programming language.
3293
4318
    """
 
4319
    takes_options = ['verbose']
3294
4320
 
3295
4321
    @display_command
3296
 
    def run(self):
 
4322
    def run(self, verbose=False):
3297
4323
        import bzrlib.plugin
3298
4324
        from inspect import getdoc
 
4325
        result = []
3299
4326
        for name, plugin in bzrlib.plugin.plugins().items():
3300
 
            print plugin.path(), "[%s]" % plugin.__version__
 
4327
            version = plugin.__version__
 
4328
            if version == 'unknown':
 
4329
                version = ''
 
4330
            name_ver = '%s %s' % (name, version)
3301
4331
            d = getdoc(plugin.module)
3302
4332
            if d:
3303
 
                print '\t', d.split('\n')[0]
 
4333
                doc = d.split('\n')[0]
 
4334
            else:
 
4335
                doc = '(no description)'
 
4336
            result.append((name_ver, doc, plugin.path()))
 
4337
        for name_ver, doc, path in sorted(result):
 
4338
            print name_ver
 
4339
            print '   ', doc
 
4340
            if verbose:
 
4341
                print '   ', path
 
4342
            print
3304
4343
 
3305
4344
 
3306
4345
class cmd_testament(Command):
3318
4357
            testament_class = StrictTestament
3319
4358
        else:
3320
4359
            testament_class = Testament
3321
 
        b = WorkingTree.open_containing(branch)[0].branch
 
4360
        if branch == '.':
 
4361
            b = Branch.open_containing(branch)[0]
 
4362
        else:
 
4363
            b = Branch.open(branch)
3322
4364
        b.lock_read()
3323
4365
        try:
3324
4366
            if revision is None:
3325
4367
                rev_id = b.last_revision()
3326
4368
            else:
3327
 
                rev_id = revision[0].in_history(b).rev_id
 
4369
                rev_id = revision[0].as_revision_id(b)
3328
4370
            t = testament_class.from_revision(b.repository, rev_id)
3329
4371
            if long:
3330
4372
                sys.stdout.writelines(t.as_text_lines())
3340
4382
    This prints out the given file with an annotation on the left side
3341
4383
    indicating which revision, author and date introduced the change.
3342
4384
 
3343
 
    If the origin is the same for a run of consecutive lines, it is 
 
4385
    If the origin is the same for a run of consecutive lines, it is
3344
4386
    shown only at the top, unless the --all option is given.
3345
4387
    """
3346
4388
    # TODO: annotate directories; showing when each file was last changed
3347
 
    # TODO: if the working copy is modified, show annotations on that 
 
4389
    # TODO: if the working copy is modified, show annotations on that
3348
4390
    #       with new uncommitted lines marked
3349
4391
    aliases = ['ann', 'blame', 'praise']
3350
4392
    takes_args = ['filename']
3358
4400
    @display_command
3359
4401
    def run(self, filename, all=False, long=False, revision=None,
3360
4402
            show_ids=False):
3361
 
        from bzrlib.annotate import annotate_file
3362
 
        tree, relpath = WorkingTree.open_containing(filename)
3363
 
        branch = tree.branch
3364
 
        branch.lock_read()
 
4403
        from bzrlib.annotate import annotate_file, annotate_file_tree
 
4404
        wt, branch, relpath = \
 
4405
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
4406
        if wt is not None:
 
4407
            wt.lock_read()
 
4408
        else:
 
4409
            branch.lock_read()
3365
4410
        try:
3366
 
            if revision is None:
3367
 
                revision_id = branch.last_revision()
3368
 
            elif len(revision) != 1:
3369
 
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
 
4411
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
 
4412
            if wt is not None:
 
4413
                file_id = wt.path2id(relpath)
3370
4414
            else:
3371
 
                revision_id = revision[0].in_history(branch).rev_id
3372
 
            file_id = tree.path2id(relpath)
 
4415
                file_id = tree.path2id(relpath)
3373
4416
            if file_id is None:
3374
4417
                raise errors.NotVersionedError(filename)
3375
 
            tree = branch.repository.revision_tree(revision_id)
3376
4418
            file_version = tree.inventory[file_id].revision
3377
 
            annotate_file(branch, file_version, file_id, long, all, self.outf,
3378
 
                          show_ids=show_ids)
 
4419
            if wt is not None and revision is None:
 
4420
                # If there is a tree and we're not annotating historical
 
4421
                # versions, annotate the working tree's content.
 
4422
                annotate_file_tree(wt, file_id, self.outf, long, all,
 
4423
                    show_ids=show_ids)
 
4424
            else:
 
4425
                annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4426
                              show_ids=show_ids)
3379
4427
        finally:
3380
 
            branch.unlock()
 
4428
            if wt is not None:
 
4429
                wt.unlock()
 
4430
            else:
 
4431
                branch.unlock()
3381
4432
 
3382
4433
 
3383
4434
class cmd_re_sign(Command):
3387
4438
    hidden = True # is this right ?
3388
4439
    takes_args = ['revision_id*']
3389
4440
    takes_options = ['revision']
3390
 
    
 
4441
 
3391
4442
    def run(self, revision_id_list=None, revision=None):
3392
 
        import bzrlib.gpg as gpg
3393
4443
        if revision_id_list is not None and revision is not None:
3394
4444
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3395
4445
        if revision_id_list is None and revision is None:
3396
4446
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3397
4447
        b = WorkingTree.open_containing(u'.')[0].branch
 
4448
        b.lock_write()
 
4449
        try:
 
4450
            return self._run(b, revision_id_list, revision)
 
4451
        finally:
 
4452
            b.unlock()
 
4453
 
 
4454
    def _run(self, b, revision_id_list, revision):
 
4455
        import bzrlib.gpg as gpg
3398
4456
        gpg_strategy = gpg.GPGStrategy(b.get_config())
3399
4457
        if revision_id_list is not None:
3400
 
            for revision_id in revision_id_list:
3401
 
                b.repository.sign_revision(revision_id, gpg_strategy)
 
4458
            b.repository.start_write_group()
 
4459
            try:
 
4460
                for revision_id in revision_id_list:
 
4461
                    b.repository.sign_revision(revision_id, gpg_strategy)
 
4462
            except:
 
4463
                b.repository.abort_write_group()
 
4464
                raise
 
4465
            else:
 
4466
                b.repository.commit_write_group()
3402
4467
        elif revision is not None:
3403
4468
            if len(revision) == 1:
3404
4469
                revno, rev_id = revision[0].in_history(b)
3405
 
                b.repository.sign_revision(rev_id, gpg_strategy)
 
4470
                b.repository.start_write_group()
 
4471
                try:
 
4472
                    b.repository.sign_revision(rev_id, gpg_strategy)
 
4473
                except:
 
4474
                    b.repository.abort_write_group()
 
4475
                    raise
 
4476
                else:
 
4477
                    b.repository.commit_write_group()
3406
4478
            elif len(revision) == 2:
3407
4479
                # are they both on rh- if so we can walk between them
3408
4480
                # might be nice to have a range helper for arbitrary
3413
4485
                    to_revno = b.revno()
3414
4486
                if from_revno is None or to_revno is None:
3415
4487
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3416
 
                for revno in range(from_revno, to_revno + 1):
3417
 
                    b.repository.sign_revision(b.get_rev_id(revno), 
3418
 
                                               gpg_strategy)
 
4488
                b.repository.start_write_group()
 
4489
                try:
 
4490
                    for revno in range(from_revno, to_revno + 1):
 
4491
                        b.repository.sign_revision(b.get_rev_id(revno),
 
4492
                                                   gpg_strategy)
 
4493
                except:
 
4494
                    b.repository.abort_write_group()
 
4495
                    raise
 
4496
                else:
 
4497
                    b.repository.commit_write_group()
3419
4498
            else:
3420
4499
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
3421
4500
 
3425
4504
 
3426
4505
    Once converted into a checkout, commits must succeed on the master branch
3427
4506
    before they will be applied to the local branch.
 
4507
 
 
4508
    Bound branches use the nickname of its master branch unless it is set
 
4509
    locally, in which case binding will update the the local nickname to be
 
4510
    that of the master.
3428
4511
    """
3429
4512
 
3430
4513
    _see_also = ['checkouts', 'unbind']
3449
4532
        except errors.DivergedBranches:
3450
4533
            raise errors.BzrCommandError('These branches have diverged.'
3451
4534
                                         ' Try merging, and then bind again.')
 
4535
        if b.get_config().has_explicit_nickname():
 
4536
            b.nick = b_other.nick
3452
4537
 
3453
4538
 
3454
4539
class cmd_unbind(Command):
3479
4564
    specified revision.  For example, "bzr uncommit -r 15" will leave the
3480
4565
    branch at revision 15.
3481
4566
 
3482
 
    In the future, uncommit will create a revision bundle, which can then
3483
 
    be re-applied.
 
4567
    Uncommit leaves the working tree ready for a new commit.  The only change
 
4568
    it may make is to restore any pending merges that were present before
 
4569
    the commit.
3484
4570
    """
3485
4571
 
3486
4572
    # TODO: jam 20060108 Add an option to allow uncommit to remove
3490
4576
    _see_also = ['commit']
3491
4577
    takes_options = ['verbose', 'revision',
3492
4578
                    Option('dry-run', help='Don\'t actually make changes.'),
3493
 
                    Option('force', help='Say yes to all questions.')]
 
4579
                    Option('force', help='Say yes to all questions.'),
 
4580
                    Option('local',
 
4581
                           help="Only remove the commits from the local branch"
 
4582
                                " when in a checkout."
 
4583
                           ),
 
4584
                    ]
3494
4585
    takes_args = ['location?']
3495
4586
    aliases = []
 
4587
    encoding_type = 'replace'
3496
4588
 
3497
4589
    def run(self, location=None,
3498
4590
            dry_run=False, verbose=False,
3499
 
            revision=None, force=False):
 
4591
            revision=None, force=False, local=False):
 
4592
        if location is None:
 
4593
            location = u'.'
 
4594
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4595
        try:
 
4596
            tree = control.open_workingtree()
 
4597
            b = tree.branch
 
4598
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
4599
            tree = None
 
4600
            b = control.open_branch()
 
4601
 
 
4602
        if tree is not None:
 
4603
            tree.lock_write()
 
4604
        else:
 
4605
            b.lock_write()
 
4606
        try:
 
4607
            return self._run(b, tree, dry_run, verbose, revision, force,
 
4608
                             local=local)
 
4609
        finally:
 
4610
            if tree is not None:
 
4611
                tree.unlock()
 
4612
            else:
 
4613
                b.unlock()
 
4614
 
 
4615
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3500
4616
        from bzrlib.log import log_formatter, show_log
3501
4617
        from bzrlib.uncommit import uncommit
3502
4618
 
3503
 
        if location is None:
3504
 
            location = u'.'
3505
 
        control, relpath = bzrdir.BzrDir.open_containing(location)
3506
 
        try:
3507
 
            tree = control.open_workingtree()
3508
 
            b = tree.branch
3509
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
3510
 
            tree = None
3511
 
            b = control.open_branch()
 
4619
        last_revno, last_rev_id = b.last_revision_info()
3512
4620
 
3513
4621
        rev_id = None
3514
4622
        if revision is None:
3515
 
            revno = b.revno()
 
4623
            revno = last_revno
 
4624
            rev_id = last_rev_id
3516
4625
        else:
3517
4626
            # 'bzr uncommit -r 10' actually means uncommit
3518
4627
            # so that the final tree is at revno 10.
3519
4628
            # but bzrlib.uncommit.uncommit() actually uncommits
3520
4629
            # the revisions that are supplied.
3521
4630
            # So we need to offset it by one
3522
 
            revno = revision[0].in_history(b).revno+1
 
4631
            revno = revision[0].in_history(b).revno + 1
 
4632
            if revno <= last_revno:
 
4633
                rev_id = b.get_rev_id(revno)
3523
4634
 
3524
 
        if revno <= b.revno():
3525
 
            rev_id = b.get_rev_id(revno)
3526
 
        if rev_id is None:
 
4635
        if rev_id is None or _mod_revision.is_null(rev_id):
3527
4636
            self.outf.write('No revisions to uncommit.\n')
3528
4637
            return 1
3529
4638
 
3536
4645
                 verbose=False,
3537
4646
                 direction='forward',
3538
4647
                 start_revision=revno,
3539
 
                 end_revision=b.revno())
 
4648
                 end_revision=last_revno)
3540
4649
 
3541
4650
        if dry_run:
3542
4651
            print 'Dry-run, pretending to remove the above revisions.'
3550
4659
                    print 'Canceled'
3551
4660
                    return 0
3552
4661
 
 
4662
        mutter('Uncommitting from {%s} to {%s}',
 
4663
               last_rev_id, rev_id)
3553
4664
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3554
 
                revno=revno)
 
4665
                 revno=revno, local=local)
 
4666
        note('You can restore the old tip by running:\n'
 
4667
             '  bzr pull . -r revid:%s', last_rev_id)
3555
4668
 
3556
4669
 
3557
4670
class cmd_break_lock(Command):
3561
4674
    holding the lock has been stopped.
3562
4675
 
3563
4676
    You can get information on what locks are open via the 'bzr info' command.
3564
 
    
 
4677
 
3565
4678
    :Examples:
3566
4679
        bzr break-lock
3567
4680
    """
3575
4688
            control.break_lock()
3576
4689
        except NotImplementedError:
3577
4690
            pass
3578
 
        
 
4691
 
3579
4692
 
3580
4693
class cmd_wait_until_signalled(Command):
3581
4694
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3599
4712
    takes_options = [
3600
4713
        Option('inet',
3601
4714
               help='Serve on stdin/out for use from inetd or sshd.'),
 
4715
        RegistryOption('protocol', 
 
4716
               help="Protocol to serve.", 
 
4717
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
 
4718
               value_switches=True),
3602
4719
        Option('port',
3603
4720
               help='Listen for connections on nominated port of the form '
3604
4721
                    '[hostname:]portnumber.  Passing 0 as the port number will '
3605
 
                    'result in a dynamically allocated port.  The default port is '
3606
 
                    '4155.',
 
4722
                    'result in a dynamically allocated port.  The default port '
 
4723
                    'depends on the protocol.',
3607
4724
               type=str),
3608
4725
        Option('directory',
3609
4726
               help='Serve contents of this directory.',
3615
4732
                ),
3616
4733
        ]
3617
4734
 
3618
 
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
3619
 
        from bzrlib.smart import medium, server
3620
 
        from bzrlib.transport import get_transport
3621
 
        from bzrlib.transport.chroot import ChrootServer
3622
 
        from bzrlib.transport.remote import BZR_DEFAULT_PORT, BZR_DEFAULT_INTERFACE
 
4735
    def get_host_and_port(self, port):
 
4736
        """Return the host and port to run the smart server on.
 
4737
 
 
4738
        If 'port' is None, None will be returned for the host and port.
 
4739
 
 
4740
        If 'port' has a colon in it, the string before the colon will be
 
4741
        interpreted as the host.
 
4742
 
 
4743
        :param port: A string of the port to run the server on.
 
4744
        :return: A tuple of (host, port), where 'host' is a host name or IP,
 
4745
            and port is an integer TCP/IP port.
 
4746
        """
 
4747
        host = None
 
4748
        if port is not None:
 
4749
            if ':' in port:
 
4750
                host, port = port.split(':')
 
4751
            port = int(port)
 
4752
        return host, port
 
4753
 
 
4754
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
 
4755
            protocol=None):
 
4756
        from bzrlib.transport import get_transport, transport_server_registry
3623
4757
        if directory is None:
3624
4758
            directory = os.getcwd()
 
4759
        if protocol is None:
 
4760
            protocol = transport_server_registry.get()
 
4761
        host, port = self.get_host_and_port(port)
3625
4762
        url = urlutils.local_path_to_url(directory)
3626
4763
        if not allow_writes:
3627
4764
            url = 'readonly+' + url
3628
 
        chroot_server = ChrootServer(get_transport(url))
3629
 
        chroot_server.setUp()
3630
 
        t = get_transport(chroot_server.get_url())
3631
 
        if inet:
3632
 
            smart_server = medium.SmartServerPipeStreamMedium(
3633
 
                sys.stdin, sys.stdout, t)
3634
 
        else:
3635
 
            host = BZR_DEFAULT_INTERFACE
3636
 
            if port is None:
3637
 
                port = BZR_DEFAULT_PORT
3638
 
            else:
3639
 
                if ':' in port:
3640
 
                    host, port = port.split(':')
3641
 
                port = int(port)
3642
 
            smart_server = server.SmartTCPServer(t, host=host, port=port)
3643
 
            print 'listening on port: ', smart_server.port
3644
 
            sys.stdout.flush()
3645
 
        # for the duration of this server, no UI output is permitted.
3646
 
        # note that this may cause problems with blackbox tests. This should
3647
 
        # be changed with care though, as we dont want to use bandwidth sending
3648
 
        # progress over stderr to smart server clients!
3649
 
        old_factory = ui.ui_factory
3650
 
        try:
3651
 
            ui.ui_factory = ui.SilentUIFactory()
3652
 
            smart_server.serve()
3653
 
        finally:
3654
 
            ui.ui_factory = old_factory
 
4765
        transport = get_transport(url)
 
4766
        protocol(transport, host, port, inet)
3655
4767
 
3656
4768
 
3657
4769
class cmd_join(Command):
3658
 
    """Combine a subtree into its containing tree.
3659
 
    
3660
 
    This command is for experimental use only.  It requires the target tree
3661
 
    to be in dirstate-with-subtree format, which cannot be converted into
3662
 
    earlier formats.
 
4770
    """Combine a tree into its containing tree.
 
4771
 
 
4772
    This command requires the target tree to be in a rich-root format.
3663
4773
 
3664
4774
    The TREE argument should be an independent tree, inside another tree, but
3665
4775
    not part of it.  (Such trees can be produced by "bzr split", but also by
3668
4778
    The result is a combined tree, with the subtree no longer an independant
3669
4779
    part.  This is marked as a merge of the subtree into the containing tree,
3670
4780
    and all history is preserved.
3671
 
 
3672
 
    If --reference is specified, the subtree retains its independence.  It can
3673
 
    be branched by itself, and can be part of multiple projects at the same
3674
 
    time.  But operations performed in the containing tree, such as commit
3675
 
    and merge, will recurse into the subtree.
3676
4781
    """
3677
4782
 
3678
4783
    _see_also = ['split']
3679
4784
    takes_args = ['tree']
3680
4785
    takes_options = [
3681
 
            Option('reference', help='Join by reference.'),
 
4786
            Option('reference', help='Join by reference.', hidden=True),
3682
4787
            ]
3683
 
    hidden = True
3684
4788
 
3685
4789
    def run(self, tree, reference=False):
3686
4790
        sub_tree = WorkingTree.open(tree)
3704
4808
            try:
3705
4809
                containing_tree.subsume(sub_tree)
3706
4810
            except errors.BadSubsumeSource, e:
3707
 
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
 
4811
                raise errors.BzrCommandError("Cannot join %s.  %s" %
3708
4812
                                             (tree, e.reason))
3709
4813
 
3710
4814
 
3711
4815
class cmd_split(Command):
3712
 
    """Split a tree into two trees.
 
4816
    """Split a subdirectory of a tree into a separate tree.
3713
4817
 
3714
 
    This command is for experimental use only.  It requires the target tree
3715
 
    to be in dirstate-with-subtree format, which cannot be converted into
3716
 
    earlier formats.
 
4818
    This command will produce a target tree in a format that supports
 
4819
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
 
4820
    converted into earlier formats like 'dirstate-tags'.
3717
4821
 
3718
4822
    The TREE argument should be a subdirectory of a working tree.  That
3719
4823
    subdirectory will be converted into an independent tree, with its own
3720
4824
    branch.  Commits in the top-level tree will not apply to the new subtree.
3721
 
    If you want that behavior, do "bzr join --reference TREE".
3722
4825
    """
3723
4826
 
3724
4827
    _see_also = ['join']
3725
4828
    takes_args = ['tree']
3726
4829
 
3727
 
    hidden = True
3728
 
 
3729
4830
    def run(self, tree):
3730
4831
        containing_tree, subdir = WorkingTree.open_containing(tree)
3731
4832
        sub_id = containing_tree.path2id(subdir)
3734
4835
        try:
3735
4836
            containing_tree.extract(sub_id)
3736
4837
        except errors.RootNotRich:
3737
 
            raise errors.UpgradeRequired(containing_tree.branch.base)
3738
 
 
 
4838
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
3739
4839
 
3740
4840
 
3741
4841
class cmd_merge_directive(Command):
3812
4912
            if len(revision) > 2:
3813
4913
                raise errors.BzrCommandError('bzr merge-directive takes '
3814
4914
                    'at most two one revision identifiers')
3815
 
            revision_id = revision[-1].in_history(branch).rev_id
 
4915
            revision_id = revision[-1].as_revision_id(branch)
3816
4916
            if len(revision) == 2:
3817
 
                base_revision_id = revision[0].in_history(branch).rev_id
3818
 
                base_revision_id = ensure_null(base_revision_id)
 
4917
                base_revision_id = revision[0].as_revision_id(branch)
3819
4918
        else:
3820
4919
            revision_id = branch.last_revision()
3821
4920
        revision_id = ensure_null(revision_id)
3839
4938
 
3840
4939
 
3841
4940
class cmd_send(Command):
3842
 
    """Mail or create a merge-directive for submiting changes.
 
4941
    """Mail or create a merge-directive for submitting changes.
3843
4942
 
3844
4943
    A merge directive provides many things needed for requesting merges:
3845
4944
 
3865
4964
    for that mirror.
3866
4965
 
3867
4966
    Mail is sent using your preferred mail program.  This should be transparent
3868
 
    on Windows (it uses MAPI).  On *nix, it requires the xdg-email utility.  If
3869
 
    the preferred client can't be found (or used), your editor will be used.
3870
 
    
 
4967
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
4968
    If the preferred client can't be found (or used), your editor will be used.
 
4969
 
3871
4970
    To use a specific mail program, set the mail_client configuration option.
3872
4971
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
3873
 
    specific clients are "evolution", "kmail", "mutt", and "thunderbird";
3874
 
    generic options are "default", "editor", "mapi", and "xdg-email".
 
4972
    specific clients are "claws", "evolution", "kmail", "mutt", and
 
4973
    "thunderbird"; generic options are "default", "editor", "emacsclient",
 
4974
    "mapi", and "xdg-email".  Plugins may also add supported clients.
3875
4975
 
3876
4976
    If mail is being sent, a to address is required.  This can be supplied
3877
 
    either on the commandline, or by setting the submit_to configuration
3878
 
    option.
 
4977
    either on the commandline, by setting the submit_to configuration
 
4978
    option in the branch itself or the child_submit_to configuration option
 
4979
    in the submit branch.
3879
4980
 
3880
4981
    Two formats are currently supported: "4" uses revision bundle format 4 and
3881
4982
    merge directive format 2.  It is significantly faster and smaller than
3882
4983
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
3883
4984
    default.  "0.9" uses revision bundle format 0.9 and merge directive
3884
4985
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
4986
 
 
4987
    The merge directives created by bzr send may be applied using bzr merge or
 
4988
    bzr pull by specifying a file containing a merge directive as the location.
3885
4989
    """
3886
4990
 
3887
4991
    encoding_type = 'exact'
3888
4992
 
3889
 
    _see_also = ['merge']
 
4993
    _see_also = ['merge', 'pull']
3890
4994
 
3891
4995
    takes_args = ['submit_branch?', 'public_branch?']
3892
4996
 
3902
5006
               'rather than the one containing the working directory.',
3903
5007
               short_name='f',
3904
5008
               type=unicode),
3905
 
        Option('output', short_name='o', help='Write directive to this file.',
 
5009
        Option('output', short_name='o',
 
5010
               help='Write merge directive to this file; '
 
5011
                    'use - for stdout.',
3906
5012
               type=unicode),
 
5013
        Option('strict',
 
5014
               help='Refuse to send if there are uncommitted changes in'
 
5015
               ' the working tree, --no-strict disables the check.'),
3907
5016
        Option('mail-to', help='Mail the request to this address.',
3908
5017
               type=unicode),
3909
5018
        'revision',
3910
5019
        'message',
3911
 
        RegistryOption.from_kwargs('format',
3912
 
        'Use the specified output format.',
3913
 
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
3914
 
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
5020
        Option('body', help='Body for the email.', type=unicode),
 
5021
        RegistryOption('format',
 
5022
                       help='Use the specified output format.',
 
5023
                       lazy_registry=('bzrlib.send', 'format_registry')),
3915
5024
        ]
3916
5025
 
3917
5026
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
3918
5027
            no_patch=False, revision=None, remember=False, output=None,
3919
 
            format='4', mail_to=None, message=None, **kwargs):
3920
 
        return self._run(submit_branch, revision, public_branch, remember,
3921
 
                         format, no_bundle, no_patch, output,
3922
 
                         kwargs.get('from', '.'), mail_to, message)
3923
 
 
3924
 
    def _run(self, submit_branch, revision, public_branch, remember, format,
3925
 
             no_bundle, no_patch, output, from_, mail_to, message):
3926
 
        from bzrlib.revision import NULL_REVISION
3927
 
        if output is None:
3928
 
            outfile = StringIO()
3929
 
        elif output == '-':
3930
 
            outfile = self.outf
3931
 
        else:
3932
 
            outfile = open(output, 'wb')
3933
 
        try:
3934
 
            branch = Branch.open_containing(from_)[0]
3935
 
            if output is None:
3936
 
                config = branch.get_config()
3937
 
                if mail_to is None:
3938
 
                    mail_to = config.get_user_option('submit_to')
3939
 
                if mail_to is None:
3940
 
                    raise errors.BzrCommandError('No mail-to address'
3941
 
                                                 ' specified')
3942
 
                mail_client = config.get_mail_client()
3943
 
            if remember and submit_branch is None:
3944
 
                raise errors.BzrCommandError(
3945
 
                    '--remember requires a branch to be specified.')
3946
 
            stored_submit_branch = branch.get_submit_branch()
3947
 
            remembered_submit_branch = False
3948
 
            if submit_branch is None:
3949
 
                submit_branch = stored_submit_branch
3950
 
                remembered_submit_branch = True
3951
 
            else:
3952
 
                if stored_submit_branch is None or remember:
3953
 
                    branch.set_submit_branch(submit_branch)
3954
 
            if submit_branch is None:
3955
 
                submit_branch = branch.get_parent()
3956
 
                remembered_submit_branch = True
3957
 
            if submit_branch is None:
3958
 
                raise errors.BzrCommandError('No submit branch known or'
3959
 
                                             ' specified')
3960
 
            if remembered_submit_branch:
3961
 
                note('Using saved location: %s', submit_branch)
3962
 
 
3963
 
            stored_public_branch = branch.get_public_branch()
3964
 
            if public_branch is None:
3965
 
                public_branch = stored_public_branch
3966
 
            elif stored_public_branch is None or remember:
3967
 
                branch.set_public_branch(public_branch)
3968
 
            if no_bundle and public_branch is None:
3969
 
                raise errors.BzrCommandError('No public branch specified or'
3970
 
                                             ' known')
3971
 
            base_revision_id = None
3972
 
            revision_id = None
3973
 
            if revision is not None:
3974
 
                if len(revision) > 2:
3975
 
                    raise errors.BzrCommandError('bzr send takes '
3976
 
                        'at most two one revision identifiers')
3977
 
                revision_id = revision[-1].in_history(branch).rev_id
3978
 
                if len(revision) == 2:
3979
 
                    base_revision_id = revision[0].in_history(branch).rev_id
3980
 
            if revision_id is None:
3981
 
                revision_id = branch.last_revision()
3982
 
            if revision_id == NULL_REVISION:
3983
 
                raise errors.BzrCommandError('No revisions to submit.')
3984
 
            if format == '4':
3985
 
                directive = merge_directive.MergeDirective2.from_objects(
3986
 
                    branch.repository, revision_id, time.time(),
3987
 
                    osutils.local_time_offset(), submit_branch,
3988
 
                    public_branch=public_branch, include_patch=not no_patch,
3989
 
                    include_bundle=not no_bundle, message=message,
3990
 
                    base_revision_id=base_revision_id)
3991
 
            elif format == '0.9':
3992
 
                if not no_bundle:
3993
 
                    if not no_patch:
3994
 
                        patch_type = 'bundle'
3995
 
                    else:
3996
 
                        raise errors.BzrCommandError('Format 0.9 does not'
3997
 
                            ' permit bundle with no patch')
3998
 
                else:
3999
 
                    if not no_patch:
4000
 
                        patch_type = 'diff'
4001
 
                    else:
4002
 
                        patch_type = None
4003
 
                directive = merge_directive.MergeDirective.from_objects(
4004
 
                    branch.repository, revision_id, time.time(),
4005
 
                    osutils.local_time_offset(), submit_branch,
4006
 
                    public_branch=public_branch, patch_type=patch_type,
4007
 
                    message=message)
4008
 
 
4009
 
            outfile.writelines(directive.to_lines())
4010
 
            if output is None:
4011
 
                subject = '[MERGE] '
4012
 
                if message is not None:
4013
 
                    subject += message
4014
 
                else:
4015
 
                    revision = branch.repository.get_revision(revision_id)
4016
 
                    subject += revision.get_summary()
4017
 
                mail_client.compose_merge_request(mail_to, subject,
4018
 
                                                  outfile.getvalue())
4019
 
        finally:
4020
 
            if output != '-':
4021
 
                outfile.close()
 
5028
            format=None, mail_to=None, message=None, body=None,
 
5029
            strict=None, **kwargs):
 
5030
        from bzrlib.send import send
 
5031
        return send(submit_branch, revision, public_branch, remember,
 
5032
                    format, no_bundle, no_patch, output,
 
5033
                    kwargs.get('from', '.'), mail_to, message, body,
 
5034
                    self.outf,
 
5035
                    strict=strict)
4022
5036
 
4023
5037
 
4024
5038
class cmd_bundle_revisions(cmd_send):
4025
 
 
4026
 
    """Create a merge-directive for submiting changes.
 
5039
    """Create a merge-directive for submitting changes.
4027
5040
 
4028
5041
    A merge directive provides many things needed for requesting merges:
4029
5042
 
4069
5082
               type=unicode),
4070
5083
        Option('output', short_name='o', help='Write directive to this file.',
4071
5084
               type=unicode),
 
5085
        Option('strict',
 
5086
               help='Refuse to bundle revisions if there are uncommitted'
 
5087
               ' changes in the working tree, --no-strict disables the check.'),
4072
5088
        'revision',
4073
 
        RegistryOption.from_kwargs('format',
4074
 
        'Use the specified output format.',
4075
 
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
4076
 
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
5089
        RegistryOption('format',
 
5090
                       help='Use the specified output format.',
 
5091
                       lazy_registry=('bzrlib.send', 'format_registry')),
4077
5092
        ]
4078
5093
    aliases = ['bundle']
4079
5094
 
4083
5098
 
4084
5099
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4085
5100
            no_patch=False, revision=None, remember=False, output=None,
4086
 
            format='4', **kwargs):
 
5101
            format=None, strict=None, **kwargs):
4087
5102
        if output is None:
4088
5103
            output = '-'
4089
 
        return self._run(submit_branch, revision, public_branch, remember,
 
5104
        from bzrlib.send import send
 
5105
        return send(submit_branch, revision, public_branch, remember,
4090
5106
                         format, no_bundle, no_patch, output,
4091
 
                         kwargs.get('from', '.'), None, None)
 
5107
                         kwargs.get('from', '.'), None, None, None,
 
5108
                         self.outf, strict=strict)
4092
5109
 
4093
5110
 
4094
5111
class cmd_tag(Command):
4095
5112
    """Create, remove or modify a tag naming a revision.
4096
 
    
 
5113
 
4097
5114
    Tags give human-meaningful names to revisions.  Commands that take a -r
4098
5115
    (--revision) option can be given -rtag:X, where X is any previously
4099
5116
    created tag.
4101
5118
    Tags are stored in the branch.  Tags are copied from one branch to another
4102
5119
    along when you branch, push, pull or merge.
4103
5120
 
4104
 
    It is an error to give a tag name that already exists unless you pass 
 
5121
    It is an error to give a tag name that already exists unless you pass
4105
5122
    --force, in which case the tag is moved to point to the new revision.
 
5123
 
 
5124
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
 
5125
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4106
5126
    """
4107
5127
 
4108
5128
    _see_also = ['commit', 'tags']
4140
5160
                        raise errors.BzrCommandError(
4141
5161
                            "Tags can only be placed on a single revision, "
4142
5162
                            "not on a range")
4143
 
                    revision_id = revision[0].in_history(branch).rev_id
 
5163
                    revision_id = revision[0].as_revision_id(branch)
4144
5164
                else:
4145
5165
                    revision_id = branch.last_revision()
4146
5166
                if (not force) and branch.tags.has_tag(tag_name):
4154
5174
class cmd_tags(Command):
4155
5175
    """List tags.
4156
5176
 
4157
 
    This tag shows a table of tag names and the revisions they reference.
 
5177
    This command shows a table of tag names and the revisions they reference.
4158
5178
    """
4159
5179
 
4160
5180
    _see_also = ['tag']
4164
5184
            short_name='d',
4165
5185
            type=unicode,
4166
5186
            ),
 
5187
        RegistryOption.from_kwargs('sort',
 
5188
            'Sort tags by different criteria.', title='Sorting',
 
5189
            alpha='Sort tags lexicographically (default).',
 
5190
            time='Sort tags chronologically.',
 
5191
            ),
 
5192
        'show-ids',
 
5193
        'revision',
4167
5194
    ]
4168
5195
 
4169
5196
    @display_command
4170
5197
    def run(self,
4171
5198
            directory='.',
 
5199
            sort='alpha',
 
5200
            show_ids=False,
 
5201
            revision=None,
4172
5202
            ):
4173
5203
        branch, relpath = Branch.open_containing(directory)
4174
 
        for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
4175
 
            self.outf.write('%-20s %s\n' % (tag_name, target))
 
5204
 
 
5205
        tags = branch.tags.get_tag_dict().items()
 
5206
        if not tags:
 
5207
            return
 
5208
 
 
5209
        branch.lock_read()
 
5210
        try:
 
5211
            if revision:
 
5212
                graph = branch.repository.get_graph()
 
5213
                rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5214
                revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5215
                # only show revisions between revid1 and revid2 (inclusive)
 
5216
                tags = [(tag, revid) for tag, revid in tags if
 
5217
                    graph.is_between(revid, revid1, revid2)]
 
5218
            if sort == 'alpha':
 
5219
                tags.sort()
 
5220
            elif sort == 'time':
 
5221
                timestamps = {}
 
5222
                for tag, revid in tags:
 
5223
                    try:
 
5224
                        revobj = branch.repository.get_revision(revid)
 
5225
                    except errors.NoSuchRevision:
 
5226
                        timestamp = sys.maxint # place them at the end
 
5227
                    else:
 
5228
                        timestamp = revobj.timestamp
 
5229
                    timestamps[revid] = timestamp
 
5230
                tags.sort(key=lambda x: timestamps[x[1]])
 
5231
            if not show_ids:
 
5232
                # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
5233
                for index, (tag, revid) in enumerate(tags):
 
5234
                    try:
 
5235
                        revno = branch.revision_id_to_dotted_revno(revid)
 
5236
                        if isinstance(revno, tuple):
 
5237
                            revno = '.'.join(map(str, revno))
 
5238
                    except errors.NoSuchRevision:
 
5239
                        # Bad tag data/merges can lead to tagged revisions
 
5240
                        # which are not in this branch. Fail gracefully ...
 
5241
                        revno = '?'
 
5242
                    tags[index] = (tag, revno)
 
5243
        finally:
 
5244
            branch.unlock()
 
5245
        for tag, revspec in tags:
 
5246
            self.outf.write('%-20s %s\n' % (tag, revspec))
4176
5247
 
4177
5248
 
4178
5249
class cmd_reconfigure(Command):
4189
5260
    If none of these is available, --bind-to must be specified.
4190
5261
    """
4191
5262
 
 
5263
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4192
5264
    takes_args = ['location?']
4193
 
    takes_options = [RegistryOption.from_kwargs('target_type',
4194
 
                     title='Target type',
4195
 
                     help='The type to reconfigure the directory to.',
4196
 
                     value_switches=True, enum_switch=False,
4197
 
                     branch='Reconfigure to a branch.',
4198
 
                     tree='Reconfigure to a tree.',
4199
 
                     checkout='Reconfigure to a checkout.'),
4200
 
                     Option('bind-to', help='Branch to bind checkout to.',
4201
 
                            type=str),
4202
 
                     Option('force',
4203
 
                        help='Perform reconfiguration even if local changes'
4204
 
                        ' will be lost.')
4205
 
                     ]
 
5265
    takes_options = [
 
5266
        RegistryOption.from_kwargs(
 
5267
            'target_type',
 
5268
            title='Target type',
 
5269
            help='The type to reconfigure the directory to.',
 
5270
            value_switches=True, enum_switch=False,
 
5271
            branch='Reconfigure to be an unbound branch with no working tree.',
 
5272
            tree='Reconfigure to be an unbound branch with a working tree.',
 
5273
            checkout='Reconfigure to be a bound branch with a working tree.',
 
5274
            lightweight_checkout='Reconfigure to be a lightweight'
 
5275
                ' checkout (with no local history).',
 
5276
            standalone='Reconfigure to be a standalone branch '
 
5277
                '(i.e. stop using shared repository).',
 
5278
            use_shared='Reconfigure to use a shared repository.',
 
5279
            with_trees='Reconfigure repository to create '
 
5280
                'working trees on branches by default.',
 
5281
            with_no_trees='Reconfigure repository to not create '
 
5282
                'working trees on branches by default.'
 
5283
            ),
 
5284
        Option('bind-to', help='Branch to bind checkout to.', type=str),
 
5285
        Option('force',
 
5286
            help='Perform reconfiguration even if local changes'
 
5287
            ' will be lost.'),
 
5288
        Option('stacked-on',
 
5289
            help='Reconfigure a branch to be stacked on another branch.',
 
5290
            type=unicode,
 
5291
            ),
 
5292
        Option('unstacked',
 
5293
            help='Reconfigure a branch to be unstacked.  This '
 
5294
                'may require copying substantial data into it.',
 
5295
            ),
 
5296
        ]
4206
5297
 
4207
 
    def run(self, location=None, target_type=None, bind_to=None, force=False):
 
5298
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5299
            stacked_on=None,
 
5300
            unstacked=None):
4208
5301
        directory = bzrdir.BzrDir.open(location)
 
5302
        if stacked_on and unstacked:
 
5303
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5304
        elif stacked_on is not None:
 
5305
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
 
5306
        elif unstacked:
 
5307
            reconfigure.ReconfigureUnstacked().apply(directory)
 
5308
        # At the moment you can use --stacked-on and a different
 
5309
        # reconfiguration shape at the same time; there seems no good reason
 
5310
        # to ban it.
4209
5311
        if target_type is None:
4210
 
            raise errors.BzrCommandError('No target configuration specified')
 
5312
            if stacked_on or unstacked:
 
5313
                return
 
5314
            else:
 
5315
                raise errors.BzrCommandError('No target configuration '
 
5316
                    'specified')
4211
5317
        elif target_type == 'branch':
4212
5318
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4213
5319
        elif target_type == 'tree':
4214
5320
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4215
5321
        elif target_type == 'checkout':
4216
 
            reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4217
 
                                                                  bind_to)
 
5322
            reconfiguration = reconfigure.Reconfigure.to_checkout(
 
5323
                directory, bind_to)
 
5324
        elif target_type == 'lightweight-checkout':
 
5325
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
 
5326
                directory, bind_to)
 
5327
        elif target_type == 'use-shared':
 
5328
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
 
5329
        elif target_type == 'standalone':
 
5330
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
 
5331
        elif target_type == 'with-trees':
 
5332
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5333
                directory, True)
 
5334
        elif target_type == 'with-no-trees':
 
5335
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5336
                directory, False)
4218
5337
        reconfiguration.apply(force)
4219
5338
 
4220
5339
 
4221
 
def _create_prefix(cur_transport):
4222
 
    needed = [cur_transport]
4223
 
    # Recurse upwards until we can create a directory successfully
4224
 
    while True:
4225
 
        new_transport = cur_transport.clone('..')
4226
 
        if new_transport.base == cur_transport.base:
4227
 
            raise errors.BzrCommandError(
4228
 
                "Failed to create path prefix for %s."
4229
 
                % cur_transport.base)
4230
 
        try:
4231
 
            new_transport.mkdir('.')
4232
 
        except errors.NoSuchFile:
4233
 
            needed.append(new_transport)
4234
 
            cur_transport = new_transport
4235
 
        else:
4236
 
            break
4237
 
    # Now we only need to create child directories
4238
 
    while needed:
4239
 
        cur_transport = needed.pop()
4240
 
        cur_transport.ensure_base()
4241
 
 
4242
 
 
4243
 
def _get_mergeable_helper(location):
4244
 
    """Get a merge directive or bundle if 'location' points to one.
4245
 
 
4246
 
    Try try to identify a bundle and returns its mergeable form. If it's not,
4247
 
    we return the tried transport anyway so that it can reused to access the
4248
 
    branch
4249
 
 
4250
 
    :param location: can point to a bundle or a branch.
4251
 
 
4252
 
    :return: mergeable, transport
4253
 
    """
4254
 
    mergeable = None
4255
 
    url = urlutils.normalize_url(location)
4256
 
    url, filename = urlutils.split(url, exclude_trailing_slash=False)
4257
 
    location_transport = transport.get_transport(url)
4258
 
    if filename:
4259
 
        try:
4260
 
            # There may be redirections but we ignore the intermediate
4261
 
            # and final transports used
4262
 
            read = bundle.read_mergeable_from_transport
4263
 
            mergeable, t = read(location_transport, filename)
4264
 
        except errors.NotABundle:
4265
 
            # Continue on considering this url a Branch but adjust the
4266
 
            # location_transport
4267
 
            location_transport = location_transport.clone(filename)
4268
 
    return mergeable, location_transport
 
5340
class cmd_switch(Command):
 
5341
    """Set the branch of a checkout and update.
 
5342
 
 
5343
    For lightweight checkouts, this changes the branch being referenced.
 
5344
    For heavyweight checkouts, this checks that there are no local commits
 
5345
    versus the current bound branch, then it makes the local branch a mirror
 
5346
    of the new location and binds to it.
 
5347
 
 
5348
    In both cases, the working tree is updated and uncommitted changes
 
5349
    are merged. The user can commit or revert these as they desire.
 
5350
 
 
5351
    Pending merges need to be committed or reverted before using switch.
 
5352
 
 
5353
    The path to the branch to switch to can be specified relative to the parent
 
5354
    directory of the current branch. For example, if you are currently in a
 
5355
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
 
5356
    /path/to/newbranch.
 
5357
 
 
5358
    Bound branches use the nickname of its master branch unless it is set
 
5359
    locally, in which case switching will update the the local nickname to be
 
5360
    that of the master.
 
5361
    """
 
5362
 
 
5363
    takes_args = ['to_location']
 
5364
    takes_options = [Option('force',
 
5365
                        help='Switch even if local commits will be lost.'),
 
5366
                     Option('create-branch', short_name='b',
 
5367
                        help='Create the target branch from this one before'
 
5368
                             ' switching to it.'),
 
5369
                     ]
 
5370
 
 
5371
    def run(self, to_location, force=False, create_branch=False):
 
5372
        from bzrlib import switch
 
5373
        tree_location = '.'
 
5374
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
 
5375
        try:
 
5376
            branch = control_dir.open_branch()
 
5377
            had_explicit_nick = branch.get_config().has_explicit_nickname()
 
5378
        except errors.NotBranchError:
 
5379
            branch = None
 
5380
            had_explicit_nick = False
 
5381
        if create_branch:
 
5382
            if branch is None:
 
5383
                raise errors.BzrCommandError('cannot create branch without'
 
5384
                                             ' source branch')
 
5385
            if '/' not in to_location and '\\' not in to_location:
 
5386
                # This path is meant to be relative to the existing branch
 
5387
                this_url = self._get_branch_location(control_dir)
 
5388
                to_location = urlutils.join(this_url, '..', to_location)
 
5389
            to_branch = branch.bzrdir.sprout(to_location,
 
5390
                                 possible_transports=[branch.bzrdir.root_transport],
 
5391
                                 source_branch=branch).open_branch()
 
5392
            # try:
 
5393
            #     from_branch = control_dir.open_branch()
 
5394
            # except errors.NotBranchError:
 
5395
            #     raise BzrCommandError('Cannot create a branch from this'
 
5396
            #         ' location when we cannot open this branch')
 
5397
            # from_branch.bzrdir.sprout(
 
5398
            pass
 
5399
        else:
 
5400
            try:
 
5401
                to_branch = Branch.open(to_location)
 
5402
            except errors.NotBranchError:
 
5403
                this_url = self._get_branch_location(control_dir)
 
5404
                to_branch = Branch.open(
 
5405
                    urlutils.join(this_url, '..', to_location))
 
5406
        switch.switch(control_dir, to_branch, force)
 
5407
        if had_explicit_nick:
 
5408
            branch = control_dir.open_branch() #get the new branch!
 
5409
            branch.nick = to_branch.nick
 
5410
        note('Switched to branch: %s',
 
5411
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
 
5412
 
 
5413
    def _get_branch_location(self, control_dir):
 
5414
        """Return location of branch for this control dir."""
 
5415
        try:
 
5416
            this_branch = control_dir.open_branch()
 
5417
            # This may be a heavy checkout, where we want the master branch
 
5418
            master_location = this_branch.get_bound_location()
 
5419
            if master_location is not None:
 
5420
                return master_location
 
5421
            # If not, use a local sibling
 
5422
            return this_branch.base
 
5423
        except errors.NotBranchError:
 
5424
            format = control_dir.find_branch_format()
 
5425
            if getattr(format, 'get_reference', None) is not None:
 
5426
                return format.get_reference(control_dir)
 
5427
            else:
 
5428
                return control_dir.root_transport.base
 
5429
 
 
5430
 
 
5431
class cmd_view(Command):
 
5432
    """Manage filtered views.
 
5433
 
 
5434
    Views provide a mask over the tree so that users can focus on
 
5435
    a subset of a tree when doing their work. After creating a view,
 
5436
    commands that support a list of files - status, diff, commit, etc -
 
5437
    effectively have that list of files implicitly given each time.
 
5438
    An explicit list of files can still be given but those files
 
5439
    must be within the current view.
 
5440
 
 
5441
    In most cases, a view has a short life-span: it is created to make
 
5442
    a selected change and is deleted once that change is committed.
 
5443
    At other times, you may wish to create one or more named views
 
5444
    and switch between them.
 
5445
 
 
5446
    To disable the current view without deleting it, you can switch to
 
5447
    the pseudo view called ``off``. This can be useful when you need
 
5448
    to see the whole tree for an operation or two (e.g. merge) but
 
5449
    want to switch back to your view after that.
 
5450
 
 
5451
    :Examples:
 
5452
      To define the current view::
 
5453
 
 
5454
        bzr view file1 dir1 ...
 
5455
 
 
5456
      To list the current view::
 
5457
 
 
5458
        bzr view
 
5459
 
 
5460
      To delete the current view::
 
5461
 
 
5462
        bzr view --delete
 
5463
 
 
5464
      To disable the current view without deleting it::
 
5465
 
 
5466
        bzr view --switch off
 
5467
 
 
5468
      To define a named view and switch to it::
 
5469
 
 
5470
        bzr view --name view-name file1 dir1 ...
 
5471
 
 
5472
      To list a named view::
 
5473
 
 
5474
        bzr view --name view-name
 
5475
 
 
5476
      To delete a named view::
 
5477
 
 
5478
        bzr view --name view-name --delete
 
5479
 
 
5480
      To switch to a named view::
 
5481
 
 
5482
        bzr view --switch view-name
 
5483
 
 
5484
      To list all views defined::
 
5485
 
 
5486
        bzr view --all
 
5487
 
 
5488
      To delete all views::
 
5489
 
 
5490
        bzr view --delete --all
 
5491
    """
 
5492
 
 
5493
    _see_also = []
 
5494
    takes_args = ['file*']
 
5495
    takes_options = [
 
5496
        Option('all',
 
5497
            help='Apply list or delete action to all views.',
 
5498
            ),
 
5499
        Option('delete',
 
5500
            help='Delete the view.',
 
5501
            ),
 
5502
        Option('name',
 
5503
            help='Name of the view to define, list or delete.',
 
5504
            type=unicode,
 
5505
            ),
 
5506
        Option('switch',
 
5507
            help='Name of the view to switch to.',
 
5508
            type=unicode,
 
5509
            ),
 
5510
        ]
 
5511
 
 
5512
    def run(self, file_list,
 
5513
            all=False,
 
5514
            delete=False,
 
5515
            name=None,
 
5516
            switch=None,
 
5517
            ):
 
5518
        tree, file_list = tree_files(file_list, apply_view=False)
 
5519
        current_view, view_dict = tree.views.get_view_info()
 
5520
        if name is None:
 
5521
            name = current_view
 
5522
        if delete:
 
5523
            if file_list:
 
5524
                raise errors.BzrCommandError(
 
5525
                    "Both --delete and a file list specified")
 
5526
            elif switch:
 
5527
                raise errors.BzrCommandError(
 
5528
                    "Both --delete and --switch specified")
 
5529
            elif all:
 
5530
                tree.views.set_view_info(None, {})
 
5531
                self.outf.write("Deleted all views.\n")
 
5532
            elif name is None:
 
5533
                raise errors.BzrCommandError("No current view to delete")
 
5534
            else:
 
5535
                tree.views.delete_view(name)
 
5536
                self.outf.write("Deleted '%s' view.\n" % name)
 
5537
        elif switch:
 
5538
            if file_list:
 
5539
                raise errors.BzrCommandError(
 
5540
                    "Both --switch and a file list specified")
 
5541
            elif all:
 
5542
                raise errors.BzrCommandError(
 
5543
                    "Both --switch and --all specified")
 
5544
            elif switch == 'off':
 
5545
                if current_view is None:
 
5546
                    raise errors.BzrCommandError("No current view to disable")
 
5547
                tree.views.set_view_info(None, view_dict)
 
5548
                self.outf.write("Disabled '%s' view.\n" % (current_view))
 
5549
            else:
 
5550
                tree.views.set_view_info(switch, view_dict)
 
5551
                view_str = views.view_display_str(tree.views.lookup_view())
 
5552
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
 
5553
        elif all:
 
5554
            if view_dict:
 
5555
                self.outf.write('Views defined:\n')
 
5556
                for view in sorted(view_dict):
 
5557
                    if view == current_view:
 
5558
                        active = "=>"
 
5559
                    else:
 
5560
                        active = "  "
 
5561
                    view_str = views.view_display_str(view_dict[view])
 
5562
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
 
5563
            else:
 
5564
                self.outf.write('No views defined.\n')
 
5565
        elif file_list:
 
5566
            if name is None:
 
5567
                # No name given and no current view set
 
5568
                name = 'my'
 
5569
            elif name == 'off':
 
5570
                raise errors.BzrCommandError(
 
5571
                    "Cannot change the 'off' pseudo view")
 
5572
            tree.views.set_view(name, sorted(file_list))
 
5573
            view_str = views.view_display_str(tree.views.lookup_view())
 
5574
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
 
5575
        else:
 
5576
            # list the files
 
5577
            if name is None:
 
5578
                # No name given and no current view set
 
5579
                self.outf.write('No current view.\n')
 
5580
            else:
 
5581
                view_str = views.view_display_str(tree.views.lookup_view(name))
 
5582
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
 
5583
 
 
5584
 
 
5585
class cmd_hooks(Command):
 
5586
    """Show hooks."""
 
5587
 
 
5588
    hidden = True
 
5589
 
 
5590
    def run(self):
 
5591
        for hook_key in sorted(hooks.known_hooks.keys()):
 
5592
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
 
5593
            self.outf.write("%s:\n" % type(some_hooks).__name__)
 
5594
            for hook_name, hook_point in sorted(some_hooks.items()):
 
5595
                self.outf.write("  %s:\n" % (hook_name,))
 
5596
                found_hooks = list(hook_point)
 
5597
                if found_hooks:
 
5598
                    for hook in found_hooks:
 
5599
                        self.outf.write("    %s\n" %
 
5600
                                        (some_hooks.get_hook_name(hook),))
 
5601
                else:
 
5602
                    self.outf.write("    <no hooks installed>\n")
 
5603
 
 
5604
 
 
5605
class cmd_shelve(Command):
 
5606
    """Temporarily set aside some changes from the current tree.
 
5607
 
 
5608
    Shelve allows you to temporarily put changes you've made "on the shelf",
 
5609
    ie. out of the way, until a later time when you can bring them back from
 
5610
    the shelf with the 'unshelve' command.  The changes are stored alongside
 
5611
    your working tree, and so they aren't propagated along with your branch nor
 
5612
    will they survive its deletion.
 
5613
 
 
5614
    If shelve --list is specified, previously-shelved changes are listed.
 
5615
 
 
5616
    Shelve is intended to help separate several sets of changes that have
 
5617
    been inappropriately mingled.  If you just want to get rid of all changes
 
5618
    and you don't need to restore them later, use revert.  If you want to
 
5619
    shelve all text changes at once, use shelve --all.
 
5620
 
 
5621
    If filenames are specified, only the changes to those files will be
 
5622
    shelved. Other files will be left untouched.
 
5623
 
 
5624
    If a revision is specified, changes since that revision will be shelved.
 
5625
 
 
5626
    You can put multiple items on the shelf, and by default, 'unshelve' will
 
5627
    restore the most recently shelved changes.
 
5628
    """
 
5629
 
 
5630
    takes_args = ['file*']
 
5631
 
 
5632
    takes_options = [
 
5633
        'revision',
 
5634
        Option('all', help='Shelve all changes.'),
 
5635
        'message',
 
5636
        RegistryOption('writer', 'Method to use for writing diffs.',
 
5637
                       bzrlib.option.diff_writer_registry,
 
5638
                       value_switches=True, enum_switch=False),
 
5639
 
 
5640
        Option('list', help='List shelved changes.'),
 
5641
        Option('destroy',
 
5642
               help='Destroy removed changes instead of shelving them.'),
 
5643
    ]
 
5644
    _see_also = ['unshelve']
 
5645
 
 
5646
    def run(self, revision=None, all=False, file_list=None, message=None,
 
5647
            writer=None, list=False, destroy=False):
 
5648
        if list:
 
5649
            return self.run_for_list()
 
5650
        from bzrlib.shelf_ui import Shelver
 
5651
        if writer is None:
 
5652
            writer = bzrlib.option.diff_writer_registry.get()
 
5653
        try:
 
5654
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
 
5655
                file_list, message, destroy=destroy)
 
5656
            try:
 
5657
                shelver.run()
 
5658
            finally:
 
5659
                shelver.work_tree.unlock()
 
5660
        except errors.UserAbort:
 
5661
            return 0
 
5662
 
 
5663
    def run_for_list(self):
 
5664
        tree = WorkingTree.open_containing('.')[0]
 
5665
        tree.lock_read()
 
5666
        try:
 
5667
            manager = tree.get_shelf_manager()
 
5668
            shelves = manager.active_shelves()
 
5669
            if len(shelves) == 0:
 
5670
                note('No shelved changes.')
 
5671
                return 0
 
5672
            for shelf_id in reversed(shelves):
 
5673
                message = manager.get_metadata(shelf_id).get('message')
 
5674
                if message is None:
 
5675
                    message = '<no message>'
 
5676
                self.outf.write('%3d: %s\n' % (shelf_id, message))
 
5677
            return 1
 
5678
        finally:
 
5679
            tree.unlock()
 
5680
 
 
5681
 
 
5682
class cmd_unshelve(Command):
 
5683
    """Restore shelved changes.
 
5684
 
 
5685
    By default, the most recently shelved changes are restored. However if you
 
5686
    specify a shelf by id those changes will be restored instead.  This works
 
5687
    best when the changes don't depend on each other.
 
5688
    """
 
5689
 
 
5690
    takes_args = ['shelf_id?']
 
5691
    takes_options = [
 
5692
        RegistryOption.from_kwargs(
 
5693
            'action', help="The action to perform.",
 
5694
            enum_switch=False, value_switches=True,
 
5695
            apply="Apply changes and remove from the shelf.",
 
5696
            dry_run="Show changes, but do not apply or remove them.",
 
5697
            delete_only="Delete changes without applying them."
 
5698
        )
 
5699
    ]
 
5700
    _see_also = ['shelve']
 
5701
 
 
5702
    def run(self, shelf_id=None, action='apply'):
 
5703
        from bzrlib.shelf_ui import Unshelver
 
5704
        unshelver = Unshelver.from_args(shelf_id, action)
 
5705
        try:
 
5706
            unshelver.run()
 
5707
        finally:
 
5708
            unshelver.tree.unlock()
 
5709
 
 
5710
 
 
5711
class cmd_clean_tree(Command):
 
5712
    """Remove unwanted files from working tree.
 
5713
 
 
5714
    By default, only unknown files, not ignored files, are deleted.  Versioned
 
5715
    files are never deleted.
 
5716
 
 
5717
    Another class is 'detritus', which includes files emitted by bzr during
 
5718
    normal operations and selftests.  (The value of these files decreases with
 
5719
    time.)
 
5720
 
 
5721
    If no options are specified, unknown files are deleted.  Otherwise, option
 
5722
    flags are respected, and may be combined.
 
5723
 
 
5724
    To check what clean-tree will do, use --dry-run.
 
5725
    """
 
5726
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5727
                     Option('detritus', help='Delete conflict files, merge'
 
5728
                            ' backups, and failed selftest dirs.'),
 
5729
                     Option('unknown',
 
5730
                            help='Delete files unknown to bzr (default).'),
 
5731
                     Option('dry-run', help='Show files to delete instead of'
 
5732
                            ' deleting them.'),
 
5733
                     Option('force', help='Do not prompt before deleting.')]
 
5734
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
 
5735
            force=False):
 
5736
        from bzrlib.clean_tree import clean_tree
 
5737
        if not (unknown or ignored or detritus):
 
5738
            unknown = True
 
5739
        if dry_run:
 
5740
            force = True
 
5741
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5742
                   dry_run=dry_run, no_prompt=force)
 
5743
 
 
5744
 
 
5745
class cmd_reference(Command):
 
5746
    """list, view and set branch locations for nested trees.
 
5747
 
 
5748
    If no arguments are provided, lists the branch locations for nested trees.
 
5749
    If one argument is provided, display the branch location for that tree.
 
5750
    If two arguments are provided, set the branch location for that tree.
 
5751
    """
 
5752
 
 
5753
    hidden = True
 
5754
 
 
5755
    takes_args = ['path?', 'location?']
 
5756
 
 
5757
    def run(self, path=None, location=None):
 
5758
        branchdir = '.'
 
5759
        if path is not None:
 
5760
            branchdir = path
 
5761
        tree, branch, relpath =(
 
5762
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
 
5763
        if path is not None:
 
5764
            path = relpath
 
5765
        if tree is None:
 
5766
            tree = branch.basis_tree()
 
5767
        if path is None:
 
5768
            info = branch._get_all_reference_info().iteritems()
 
5769
            self._display_reference_info(tree, branch, info)
 
5770
        else:
 
5771
            file_id = tree.path2id(path)
 
5772
            if file_id is None:
 
5773
                raise errors.NotVersionedError(path)
 
5774
            if location is None:
 
5775
                info = [(file_id, branch.get_reference_info(file_id))]
 
5776
                self._display_reference_info(tree, branch, info)
 
5777
            else:
 
5778
                branch.set_reference_info(file_id, path, location)
 
5779
 
 
5780
    def _display_reference_info(self, tree, branch, info):
 
5781
        ref_list = []
 
5782
        for file_id, (path, location) in info:
 
5783
            try:
 
5784
                path = tree.id2path(file_id)
 
5785
            except errors.NoSuchId:
 
5786
                pass
 
5787
            ref_list.append((path, location))
 
5788
        for path, location in sorted(ref_list):
 
5789
            self.outf.write('%s %s\n' % (path, location))
4269
5790
 
4270
5791
 
4271
5792
# these get imported and then picked up by the scan for cmd_*
4272
5793
# TODO: Some more consistent way to split command definitions across files;
4273
 
# we do need to load at least some information about them to know of 
 
5794
# we do need to load at least some information about them to know of
4274
5795
# aliases.  ideally we would avoid loading the implementation until the
4275
5796
# details were needed.
4276
5797
from bzrlib.cmd_version_info import cmd_version_info
4278
5799
from bzrlib.bundle.commands import (
4279
5800
    cmd_bundle_info,
4280
5801
    )
 
5802
from bzrlib.foreign import cmd_dpush
4281
5803
from bzrlib.sign_my_commits import cmd_sign_my_commits
4282
 
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
 
5804
from bzrlib.weave_commands import cmd_versionedfile_list, \
4283
5805
        cmd_weave_plan_merge, cmd_weave_merge_text