~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Andrew Bennetts
  • Date: 2009-08-07 04:17:51 UTC
  • mto: This revision was merged to the branch mainline in revision 4608.
  • Revision ID: andrew.bennetts@canonical.com-20090807041751-0vhb0y0g7k49hr45
Review comments from John.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 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
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
 
23
import codecs
23
24
import cStringIO
24
25
import sys
25
26
import time
30
31
    bundle,
31
32
    btree_index,
32
33
    bzrdir,
33
 
    directory_service,
34
34
    delta,
35
 
    config as _mod_config,
 
35
    config,
36
36
    errors,
37
37
    globbing,
38
38
    hooks,
43
43
    reconfigure,
44
44
    rename_map,
45
45
    revision as _mod_revision,
46
 
    static_tuple,
47
 
    timestamp,
 
46
    symbol_versioning,
48
47
    transport,
49
48
    ui,
50
49
    urlutils,
51
50
    views,
52
 
    gpg,
53
51
    )
54
52
from bzrlib.branch import Branch
55
53
from bzrlib.conflicts import ConflictList
56
 
from bzrlib.transport import memory
57
54
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
58
55
from bzrlib.smtp_connection import SMTPConnection
59
56
from bzrlib.workingtree import WorkingTree
60
57
""")
61
58
 
62
 
from bzrlib.commands import (
63
 
    Command,
64
 
    builtin_command_registry,
65
 
    display_command,
66
 
    )
 
59
from bzrlib.commands import Command, display_command
67
60
from bzrlib.option import (
68
61
    ListOption,
69
62
    Option,
72
65
    _parse_revision_str,
73
66
    )
74
67
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
75
 
from bzrlib import (
76
 
    symbol_versioning,
77
 
    )
78
 
 
79
 
 
80
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
 
68
 
 
69
 
81
70
def tree_files(file_list, default_branch=u'.', canonicalize=True,
82
71
    apply_view=True):
83
 
    return internal_tree_files(file_list, default_branch, canonicalize,
84
 
        apply_view)
 
72
    try:
 
73
        return internal_tree_files(file_list, default_branch, canonicalize,
 
74
            apply_view)
 
75
    except errors.FileInWrongBranch, e:
 
76
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
 
77
                                     (e.path, file_list[0]))
85
78
 
86
79
 
87
80
def tree_files_for_add(file_list):
127
120
 
128
121
 
129
122
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
130
 
    """Get a revision tree. Not suitable for commands that change the tree.
131
 
    
132
 
    Specifically, the basis tree in dirstate trees is coupled to the dirstate
133
 
    and doing a commit/uncommit/pull will at best fail due to changing the
134
 
    basis revision data.
135
 
 
136
 
    If tree is passed in, it should be already locked, for lifetime management
137
 
    of the trees internal cached state.
138
 
    """
139
123
    if branch is None:
140
124
        branch = tree.branch
141
125
    if revisions is None:
151
135
 
152
136
# XXX: Bad function name; should possibly also be a class method of
153
137
# WorkingTree rather than a function.
154
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
155
138
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
156
139
    apply_view=True):
157
140
    """Convert command-line paths to a WorkingTree and relative paths.
158
141
 
159
 
    Deprecated: use WorkingTree.open_containing_paths instead.
160
 
 
161
142
    This is typically used for command-line processors that take one or
162
143
    more filenames, and infer the workingtree that contains them.
163
144
 
173
154
 
174
155
    :return: workingtree, [relative_paths]
175
156
    """
176
 
    return WorkingTree.open_containing_paths(
177
 
        file_list, default_directory='.',
178
 
        canonicalize=True,
179
 
        apply_view=True)
 
157
    if file_list is None or len(file_list) == 0:
 
158
        tree = WorkingTree.open_containing(default_branch)[0]
 
159
        if tree.supports_views() and apply_view:
 
160
            view_files = tree.views.lookup_view()
 
161
            if view_files:
 
162
                file_list = view_files
 
163
                view_str = views.view_display_str(view_files)
 
164
                note("Ignoring files outside view. View is %s" % view_str)
 
165
        return tree, file_list
 
166
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
167
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
168
        apply_view=apply_view)
 
169
 
 
170
 
 
171
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
 
172
    """Convert file_list into a list of relpaths in tree.
 
173
 
 
174
    :param tree: A tree to operate on.
 
175
    :param file_list: A list of user provided paths or None.
 
176
    :param apply_view: if True and a view is set, apply it or check that
 
177
        specified files are within it
 
178
    :return: A list of relative paths.
 
179
    :raises errors.PathNotChild: When a provided path is in a different tree
 
180
        than tree.
 
181
    """
 
182
    if file_list is None:
 
183
        return None
 
184
    if tree.supports_views() and apply_view:
 
185
        view_files = tree.views.lookup_view()
 
186
    else:
 
187
        view_files = []
 
188
    new_list = []
 
189
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
 
190
    # doesn't - fix that up here before we enter the loop.
 
191
    if canonicalize:
 
192
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
 
193
    else:
 
194
        fixer = tree.relpath
 
195
    for filename in file_list:
 
196
        try:
 
197
            relpath = fixer(osutils.dereference_path(filename))
 
198
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
199
                raise errors.FileOutsideView(filename, view_files)
 
200
            new_list.append(relpath)
 
201
        except errors.PathNotChild:
 
202
            raise errors.FileInWrongBranch(tree.branch, filename)
 
203
    return new_list
180
204
 
181
205
 
182
206
def _get_view_info_for_change_reporter(tree):
191
215
    return view_info
192
216
 
193
217
 
194
 
def _open_directory_or_containing_tree_or_branch(filename, directory):
195
 
    """Open the tree or branch containing the specified file, unless
196
 
    the --directory option is used to specify a different branch."""
197
 
    if directory is not None:
198
 
        return (None, Branch.open(directory), filename)
199
 
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
200
 
 
201
 
 
202
218
# TODO: Make sure no commands unconditionally use the working directory as a
203
219
# branch.  If a filename argument is used, the first of them should be used to
204
220
# specify the branch.  (Perhaps this can be factored out into some kind of
206
222
# opens the branch?)
207
223
 
208
224
class cmd_status(Command):
209
 
    __doc__ = """Display status summary.
 
225
    """Display status summary.
210
226
 
211
227
    This reports on versioned and unknown files, reporting them
212
228
    grouped by state.  Possible states are:
232
248
    unknown
233
249
        Not versioned and not matching an ignore pattern.
234
250
 
235
 
    Additionally for directories, symlinks and files with an executable
236
 
    bit, Bazaar indicates their type using a trailing character: '/', '@'
237
 
    or '*' respectively.
238
 
 
239
251
    To see ignored files use 'bzr ignored'.  For details on the
240
252
    changes to file texts, use 'bzr diff'.
241
253
 
253
265
    To skip the display of pending merge information altogether, use
254
266
    the no-pending option or specify a file/directory.
255
267
 
256
 
    To compare the working directory to a specific revision, pass a
257
 
    single revision to the revision argument.
258
 
 
259
 
    To see which files have changed in a specific revision, or between
260
 
    two revisions, pass a revision range to the revision argument.
261
 
    This will produce the same results as calling 'bzr diff --summarize'.
 
268
    If a revision argument is given, the status is calculated against
 
269
    that revision, or between two revisions if two are provided.
262
270
    """
263
271
 
264
272
    # TODO: --no-recurse, --recurse options
286
294
            raise errors.BzrCommandError('bzr status --revision takes exactly'
287
295
                                         ' one or two revision specifiers')
288
296
 
289
 
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
297
        tree, relfile_list = tree_files(file_list)
290
298
        # Avoid asking for specific files when that is not needed.
291
299
        if relfile_list == ['']:
292
300
            relfile_list = None
303
311
 
304
312
 
305
313
class cmd_cat_revision(Command):
306
 
    __doc__ = """Write out metadata for a revision.
 
314
    """Write out metadata for a revision.
307
315
 
308
316
    The revision to print can either be specified by a specific
309
317
    revision identifier, or you can use --revision.
311
319
 
312
320
    hidden = True
313
321
    takes_args = ['revision_id?']
314
 
    takes_options = ['directory', 'revision']
 
322
    takes_options = ['revision']
315
323
    # cat-revision is more for frontends so should be exact
316
324
    encoding = 'strict'
317
325
 
318
 
    def print_revision(self, revisions, revid):
319
 
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
320
 
        record = stream.next()
321
 
        if record.storage_kind == 'absent':
322
 
            raise errors.NoSuchRevision(revisions, revid)
323
 
        revtext = record.get_bytes_as('fulltext')
324
 
        self.outf.write(revtext.decode('utf-8'))
325
 
 
326
326
    @display_command
327
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
327
    def run(self, revision_id=None, revision=None):
328
328
        if revision_id is not None and revision is not None:
329
329
            raise errors.BzrCommandError('You can only supply one of'
330
330
                                         ' revision_id or --revision')
331
331
        if revision_id is None and revision is None:
332
332
            raise errors.BzrCommandError('You must supply either'
333
333
                                         ' --revision or a revision_id')
334
 
 
335
 
        b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
336
 
 
337
 
        revisions = b.repository.revisions
338
 
        if revisions is None:
339
 
            raise errors.BzrCommandError('Repository %r does not support '
340
 
                'access to raw revision texts')
341
 
 
342
 
        b.repository.lock_read()
343
 
        try:
344
 
            # TODO: jam 20060112 should cat-revision always output utf-8?
345
 
            if revision_id is not None:
346
 
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
347
 
                try:
348
 
                    self.print_revision(revisions, revision_id)
349
 
                except errors.NoSuchRevision:
350
 
                    msg = "The repository %s contains no revision %s." % (
351
 
                        b.repository.base, revision_id)
352
 
                    raise errors.BzrCommandError(msg)
353
 
            elif revision is not None:
354
 
                for rev in revision:
355
 
                    if rev is None:
356
 
                        raise errors.BzrCommandError(
357
 
                            'You cannot specify a NULL revision.')
358
 
                    rev_id = rev.as_revision_id(b)
359
 
                    self.print_revision(revisions, rev_id)
360
 
        finally:
361
 
            b.repository.unlock()
362
 
        
 
334
        b = WorkingTree.open_containing(u'.')[0].branch
 
335
 
 
336
        # TODO: jam 20060112 should cat-revision always output utf-8?
 
337
        if revision_id is not None:
 
338
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
 
339
            try:
 
340
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
341
            except errors.NoSuchRevision:
 
342
                msg = "The repository %s contains no revision %s." % (b.repository.base,
 
343
                    revision_id)
 
344
                raise errors.BzrCommandError(msg)
 
345
        elif revision is not None:
 
346
            for rev in revision:
 
347
                if rev is None:
 
348
                    raise errors.BzrCommandError('You cannot specify a NULL'
 
349
                                                 ' revision.')
 
350
                rev_id = rev.as_revision_id(b)
 
351
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
 
352
 
363
353
 
364
354
class cmd_dump_btree(Command):
365
 
    __doc__ = """Dump the contents of a btree index file to stdout.
 
355
    """Dump the contents of a btree index file to stdout.
366
356
 
367
357
    PATH is a btree index file, it can be any URL. This includes things like
368
358
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
416
406
                self.outf.write(page_bytes[:header_end])
417
407
                page_bytes = data
418
408
            self.outf.write('\nPage %d\n' % (page_idx,))
419
 
            if len(page_bytes) == 0:
420
 
                self.outf.write('(empty)\n');
421
 
            else:
422
 
                decomp_bytes = zlib.decompress(page_bytes)
423
 
                self.outf.write(decomp_bytes)
424
 
                self.outf.write('\n')
 
409
            decomp_bytes = zlib.decompress(page_bytes)
 
410
            self.outf.write(decomp_bytes)
 
411
            self.outf.write('\n')
425
412
 
426
413
    def _dump_entries(self, trans, basename):
427
414
        try:
435
422
        for node in bt.iter_all_entries():
436
423
            # Node is made up of:
437
424
            # (index, key, value, [references])
438
 
            try:
439
 
                refs = node[3]
440
 
            except IndexError:
441
 
                refs_as_tuples = None
442
 
            else:
443
 
                refs_as_tuples = static_tuple.as_tuples(refs)
444
 
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
445
 
            self.outf.write('%s\n' % (as_tuple,))
 
425
            self.outf.write('%s\n' % (node[1:],))
446
426
 
447
427
 
448
428
class cmd_remove_tree(Command):
449
 
    __doc__ = """Remove the working tree from a given branch/checkout.
 
429
    """Remove the working tree from a given branch/checkout.
450
430
 
451
431
    Since a lightweight checkout is little more than a working tree
452
432
    this will refuse to run against one.
454
434
    To re-create the working tree, use "bzr checkout".
455
435
    """
456
436
    _see_also = ['checkout', 'working-trees']
457
 
    takes_args = ['location*']
 
437
    takes_args = ['location?']
458
438
    takes_options = [
459
439
        Option('force',
460
440
               help='Remove the working tree even if it has '
461
 
                    'uncommitted or shelved changes.'),
 
441
                    'uncommitted changes.'),
462
442
        ]
463
443
 
464
 
    def run(self, location_list, force=False):
465
 
        if not location_list:
466
 
            location_list=['.']
467
 
 
468
 
        for location in location_list:
469
 
            d = bzrdir.BzrDir.open(location)
470
 
            
471
 
            try:
472
 
                working = d.open_workingtree()
473
 
            except errors.NoWorkingTree:
474
 
                raise errors.BzrCommandError("No working tree to remove")
475
 
            except errors.NotLocalUrl:
476
 
                raise errors.BzrCommandError("You cannot remove the working tree"
477
 
                                             " of a remote path")
478
 
            if not force:
479
 
                if (working.has_changes()):
480
 
                    raise errors.UncommittedChanges(working)
481
 
                if working.get_shelf_manager().last_shelf() is not None:
482
 
                    raise errors.ShelvedChanges(working)
483
 
 
484
 
            if working.user_url != working.branch.user_url:
485
 
                raise errors.BzrCommandError("You cannot remove the working tree"
486
 
                                             " from a lightweight checkout")
487
 
 
488
 
            d.destroy_workingtree()
489
 
 
490
 
 
491
 
class cmd_repair_workingtree(Command):
492
 
    __doc__ = """Reset the working tree state file.
493
 
 
494
 
    This is not meant to be used normally, but more as a way to recover from
495
 
    filesystem corruption, etc. This rebuilds the working inventory back to a
496
 
    'known good' state. Any new modifications (adding a file, renaming, etc)
497
 
    will be lost, though modified files will still be detected as such.
498
 
 
499
 
    Most users will want something more like "bzr revert" or "bzr update"
500
 
    unless the state file has become corrupted.
501
 
 
502
 
    By default this attempts to recover the current state by looking at the
503
 
    headers of the state file. If the state file is too corrupted to even do
504
 
    that, you can supply --revision to force the state of the tree.
505
 
    """
506
 
 
507
 
    takes_options = ['revision', 'directory',
508
 
        Option('force',
509
 
               help='Reset the tree even if it doesn\'t appear to be'
510
 
                    ' corrupted.'),
511
 
    ]
512
 
    hidden = True
513
 
 
514
 
    def run(self, revision=None, directory='.', force=False):
515
 
        tree, _ = WorkingTree.open_containing(directory)
516
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
444
    def run(self, location='.', force=False):
 
445
        d = bzrdir.BzrDir.open(location)
 
446
 
 
447
        try:
 
448
            working = d.open_workingtree()
 
449
        except errors.NoWorkingTree:
 
450
            raise errors.BzrCommandError("No working tree to remove")
 
451
        except errors.NotLocalUrl:
 
452
            raise errors.BzrCommandError("You cannot remove the working tree"
 
453
                                         " of a remote path")
517
454
        if not force:
518
 
            try:
519
 
                tree.check_state()
520
 
            except errors.BzrError:
521
 
                pass # There seems to be a real error here, so we'll reset
522
 
            else:
523
 
                # Refuse
524
 
                raise errors.BzrCommandError(
525
 
                    'The tree does not appear to be corrupt. You probably'
526
 
                    ' want "bzr revert" instead. Use "--force" if you are'
527
 
                    ' sure you want to reset the working tree.')
528
 
        if revision is None:
529
 
            revision_ids = None
530
 
        else:
531
 
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
532
 
        try:
533
 
            tree.reset_state(revision_ids)
534
 
        except errors.BzrError, e:
535
 
            if revision_ids is None:
536
 
                extra = (', the header appears corrupt, try passing -r -1'
537
 
                         ' to set the state to the last commit')
538
 
            else:
539
 
                extra = ''
540
 
            raise errors.BzrCommandError('failed to reset the tree state'
541
 
                                         + extra)
 
455
            # XXX: What about pending merges ? -- vila 20090629
 
456
            if working.has_changes(working.basis_tree()):
 
457
                raise errors.UncommittedChanges(working)
 
458
 
 
459
        working_path = working.bzrdir.root_transport.base
 
460
        branch_path = working.branch.bzrdir.root_transport.base
 
461
        if working_path != branch_path:
 
462
            raise errors.BzrCommandError("You cannot remove the working tree"
 
463
                                         " from a lightweight checkout")
 
464
 
 
465
        d.destroy_workingtree()
542
466
 
543
467
 
544
468
class cmd_revno(Command):
545
 
    __doc__ = """Show current revision number.
 
469
    """Show current revision number.
546
470
 
547
471
    This is equal to the number of revisions on this branch.
548
472
    """
558
482
        if tree:
559
483
            try:
560
484
                wt = WorkingTree.open_containing(location)[0]
561
 
                self.add_cleanup(wt.lock_read().unlock)
 
485
                wt.lock_read()
562
486
            except (errors.NoWorkingTree, errors.NotLocalUrl):
563
487
                raise errors.NoWorkingTree(location)
564
 
            revid = wt.last_revision()
565
488
            try:
566
 
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
567
 
            except errors.NoSuchRevision:
568
 
                revno_t = ('???',)
569
 
            revno = ".".join(str(n) for n in revno_t)
 
489
                revid = wt.last_revision()
 
490
                try:
 
491
                    revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
492
                except errors.NoSuchRevision:
 
493
                    revno_t = ('???',)
 
494
                revno = ".".join(str(n) for n in revno_t)
 
495
            finally:
 
496
                wt.unlock()
570
497
        else:
571
498
            b = Branch.open_containing(location)[0]
572
 
            self.add_cleanup(b.lock_read().unlock)
573
 
            revno = b.revno()
574
 
        self.cleanup_now()
 
499
            b.lock_read()
 
500
            try:
 
501
                revno = b.revno()
 
502
            finally:
 
503
                b.unlock()
 
504
 
575
505
        self.outf.write(str(revno) + '\n')
576
506
 
577
507
 
578
508
class cmd_revision_info(Command):
579
 
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
509
    """Show revision number and revision id for a given revision identifier.
580
510
    """
581
511
    hidden = True
582
512
    takes_args = ['revision_info*']
583
513
    takes_options = [
584
514
        'revision',
585
 
        custom_help('directory',
 
515
        Option('directory',
586
516
            help='Branch to examine, '
587
 
                 'rather than the one containing the working directory.'),
 
517
                 'rather than the one containing the working directory.',
 
518
            short_name='d',
 
519
            type=unicode,
 
520
            ),
588
521
        Option('tree', help='Show revno of working tree'),
589
522
        ]
590
523
 
595
528
        try:
596
529
            wt = WorkingTree.open_containing(directory)[0]
597
530
            b = wt.branch
598
 
            self.add_cleanup(wt.lock_read().unlock)
 
531
            wt.lock_read()
599
532
        except (errors.NoWorkingTree, errors.NotLocalUrl):
600
533
            wt = None
601
534
            b = Branch.open_containing(directory)[0]
602
 
            self.add_cleanup(b.lock_read().unlock)
603
 
        revision_ids = []
604
 
        if revision is not None:
605
 
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
606
 
        if revision_info_list is not None:
607
 
            for rev_str in revision_info_list:
608
 
                rev_spec = RevisionSpec.from_string(rev_str)
609
 
                revision_ids.append(rev_spec.as_revision_id(b))
610
 
        # No arguments supplied, default to the last revision
611
 
        if len(revision_ids) == 0:
612
 
            if tree:
613
 
                if wt is None:
614
 
                    raise errors.NoWorkingTree(directory)
615
 
                revision_ids.append(wt.last_revision())
 
535
            b.lock_read()
 
536
        try:
 
537
            revision_ids = []
 
538
            if revision is not None:
 
539
                revision_ids.extend(rev.as_revision_id(b) for rev in revision)
 
540
            if revision_info_list is not None:
 
541
                for rev_str in revision_info_list:
 
542
                    rev_spec = RevisionSpec.from_string(rev_str)
 
543
                    revision_ids.append(rev_spec.as_revision_id(b))
 
544
            # No arguments supplied, default to the last revision
 
545
            if len(revision_ids) == 0:
 
546
                if tree:
 
547
                    if wt is None:
 
548
                        raise errors.NoWorkingTree(directory)
 
549
                    revision_ids.append(wt.last_revision())
 
550
                else:
 
551
                    revision_ids.append(b.last_revision())
 
552
 
 
553
            revinfos = []
 
554
            maxlen = 0
 
555
            for revision_id in revision_ids:
 
556
                try:
 
557
                    dotted_revno = b.revision_id_to_dotted_revno(revision_id)
 
558
                    revno = '.'.join(str(i) for i in dotted_revno)
 
559
                except errors.NoSuchRevision:
 
560
                    revno = '???'
 
561
                maxlen = max(maxlen, len(revno))
 
562
                revinfos.append([revno, revision_id])
 
563
        finally:
 
564
            if wt is None:
 
565
                b.unlock()
616
566
            else:
617
 
                revision_ids.append(b.last_revision())
618
 
 
619
 
        revinfos = []
620
 
        maxlen = 0
621
 
        for revision_id in revision_ids:
622
 
            try:
623
 
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
624
 
                revno = '.'.join(str(i) for i in dotted_revno)
625
 
            except errors.NoSuchRevision:
626
 
                revno = '???'
627
 
            maxlen = max(maxlen, len(revno))
628
 
            revinfos.append([revno, revision_id])
629
 
 
630
 
        self.cleanup_now()
 
567
                wt.unlock()
 
568
 
631
569
        for ri in revinfos:
632
570
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
633
571
 
634
572
 
635
573
class cmd_add(Command):
636
 
    __doc__ = """Add specified files or directories.
 
574
    """Add specified files or directories.
637
575
 
638
576
    In non-recursive mode, all the named items are added, regardless
639
577
    of whether they were previously ignored.  A warning is given if
665
603
    branches that will be merged later (without showing the two different
666
604
    adds as a conflict). It is also useful when merging another project
667
605
    into a subdirectory of this one.
668
 
    
669
 
    Any files matching patterns in the ignore list will not be added
670
 
    unless they are explicitly mentioned.
671
606
    """
672
607
    takes_args = ['file*']
673
608
    takes_options = [
681
616
               help='Lookup file ids from this tree.'),
682
617
        ]
683
618
    encoding_type = 'replace'
684
 
    _see_also = ['remove', 'ignore']
 
619
    _see_also = ['remove']
685
620
 
686
621
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
687
622
            file_ids_from=None):
704
639
                should_print=(not is_quiet()))
705
640
 
706
641
        if base_tree:
707
 
            self.add_cleanup(base_tree.lock_read().unlock)
708
 
        tree, file_list = tree_files_for_add(file_list)
709
 
        added, ignored = tree.smart_add(file_list, not
710
 
            no_recurse, action=action, save=not dry_run)
711
 
        self.cleanup_now()
 
642
            base_tree.lock_read()
 
643
        try:
 
644
            file_list = self._maybe_expand_globs(file_list)
 
645
            tree, file_list = tree_files_for_add(file_list)
 
646
            added, ignored = tree.smart_add(file_list, not
 
647
                no_recurse, action=action, save=not dry_run)
 
648
        finally:
 
649
            if base_tree is not None:
 
650
                base_tree.unlock()
712
651
        if len(ignored) > 0:
713
652
            if verbose:
714
653
                for glob in sorted(ignored.keys()):
715
654
                    for path in ignored[glob]:
716
655
                        self.outf.write("ignored %s matching \"%s\"\n"
717
656
                                        % (path, glob))
 
657
            else:
 
658
                match_len = 0
 
659
                for glob, paths in ignored.items():
 
660
                    match_len += len(paths)
 
661
                self.outf.write("ignored %d file(s).\n" % match_len)
 
662
            self.outf.write("If you wish to add ignored files, "
 
663
                            "please add them explicitly by name. "
 
664
                            "(\"bzr ignored\" gives a list)\n")
718
665
 
719
666
 
720
667
class cmd_mkdir(Command):
721
 
    __doc__ = """Create a new versioned directory.
 
668
    """Create a new versioned directory.
722
669
 
723
670
    This is equivalent to creating the directory and then adding it.
724
671
    """
728
675
 
729
676
    def run(self, dir_list):
730
677
        for d in dir_list:
 
678
            os.mkdir(d)
731
679
            wt, dd = WorkingTree.open_containing(d)
732
 
            base = os.path.dirname(dd)
733
 
            id = wt.path2id(base)
734
 
            if id != None:
735
 
                os.mkdir(d)
736
 
                wt.add([dd])
737
 
                self.outf.write('added %s\n' % d)
738
 
            else:
739
 
                raise errors.NotVersionedError(path=base)
 
680
            wt.add([dd])
 
681
            self.outf.write('added %s\n' % d)
740
682
 
741
683
 
742
684
class cmd_relpath(Command):
743
 
    __doc__ = """Show path of a file relative to root"""
 
685
    """Show path of a file relative to root"""
744
686
 
745
687
    takes_args = ['filename']
746
688
    hidden = True
755
697
 
756
698
 
757
699
class cmd_inventory(Command):
758
 
    __doc__ = """Show inventory of the current working copy or a revision.
 
700
    """Show inventory of the current working copy or a revision.
759
701
 
760
702
    It is possible to limit the output to a particular entry
761
703
    type using the --kind option.  For example: --kind file.
781
723
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
782
724
 
783
725
        revision = _get_one_revision('inventory', revision)
784
 
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
785
 
        self.add_cleanup(work_tree.lock_read().unlock)
786
 
        if revision is not None:
787
 
            tree = revision.as_tree(work_tree.branch)
788
 
 
789
 
            extra_trees = [work_tree]
790
 
            self.add_cleanup(tree.lock_read().unlock)
791
 
        else:
792
 
            tree = work_tree
793
 
            extra_trees = []
794
 
 
795
 
        if file_list is not None:
796
 
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
797
 
                                      require_versioned=True)
798
 
            # find_ids_across_trees may include some paths that don't
799
 
            # exist in 'tree'.
800
 
            entries = sorted(
801
 
                (tree.id2path(file_id), tree.inventory[file_id])
802
 
                for file_id in file_ids if tree.has_id(file_id))
803
 
        else:
804
 
            entries = tree.inventory.entries()
805
 
 
806
 
        self.cleanup_now()
 
726
        work_tree, file_list = tree_files(file_list)
 
727
        work_tree.lock_read()
 
728
        try:
 
729
            if revision is not None:
 
730
                tree = revision.as_tree(work_tree.branch)
 
731
 
 
732
                extra_trees = [work_tree]
 
733
                tree.lock_read()
 
734
            else:
 
735
                tree = work_tree
 
736
                extra_trees = []
 
737
 
 
738
            if file_list is not None:
 
739
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
740
                                          require_versioned=True)
 
741
                # find_ids_across_trees may include some paths that don't
 
742
                # exist in 'tree'.
 
743
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
744
                                 for file_id in file_ids if file_id in tree)
 
745
            else:
 
746
                entries = tree.inventory.entries()
 
747
        finally:
 
748
            tree.unlock()
 
749
            if tree is not work_tree:
 
750
                work_tree.unlock()
 
751
 
807
752
        for path, entry in entries:
808
753
            if kind and kind != entry.kind:
809
754
                continue
815
760
 
816
761
 
817
762
class cmd_mv(Command):
818
 
    __doc__ = """Move or rename a file.
 
763
    """Move or rename a file.
819
764
 
820
765
    :Usage:
821
766
        bzr mv OLDNAME NEWNAME
853
798
            names_list = []
854
799
        if len(names_list) < 2:
855
800
            raise errors.BzrCommandError("missing file argument")
856
 
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
857
 
        self.add_cleanup(tree.lock_tree_write().unlock)
858
 
        self._run(tree, names_list, rel_names, after)
 
801
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
802
        tree.lock_tree_write()
 
803
        try:
 
804
            self._run(tree, names_list, rel_names, after)
 
805
        finally:
 
806
            tree.unlock()
859
807
 
860
808
    def run_auto(self, names_list, after, dry_run):
861
809
        if names_list is not None and len(names_list) > 1:
864
812
        if after:
865
813
            raise errors.BzrCommandError('--after cannot be specified with'
866
814
                                         ' --auto.')
867
 
        work_tree, file_list = WorkingTree.open_containing_paths(
868
 
            names_list, default_directory='.')
869
 
        self.add_cleanup(work_tree.lock_tree_write().unlock)
870
 
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
815
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
816
        work_tree.lock_tree_write()
 
817
        try:
 
818
            rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
819
        finally:
 
820
            work_tree.unlock()
871
821
 
872
822
    def _run(self, tree, names_list, rel_names, after):
873
823
        into_existing = osutils.isdir(names_list[-1])
894
844
            # All entries reference existing inventory items, so fix them up
895
845
            # for cicp file-systems.
896
846
            rel_names = tree.get_canonical_inventory_paths(rel_names)
897
 
            for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
898
 
                if not is_quiet():
899
 
                    self.outf.write("%s => %s\n" % (src, dest))
 
847
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
 
848
                self.outf.write("%s => %s\n" % pair)
900
849
        else:
901
850
            if len(names_list) != 2:
902
851
                raise errors.BzrCommandError('to mv multiple files the'
946
895
            dest = osutils.pathjoin(dest_parent, dest_tail)
947
896
            mutter("attempting to move %s => %s", src, dest)
948
897
            tree.rename_one(src, dest, after=after)
949
 
            if not is_quiet():
950
 
                self.outf.write("%s => %s\n" % (src, dest))
 
898
            self.outf.write("%s => %s\n" % (src, dest))
951
899
 
952
900
 
953
901
class cmd_pull(Command):
954
 
    __doc__ = """Turn this branch into a mirror of another branch.
 
902
    """Turn this branch into a mirror of another branch.
955
903
 
956
 
    By default, this command only works on branches that have not diverged.
957
 
    Branches are considered diverged if the destination branch's most recent 
958
 
    commit is one that has not been merged (directly or indirectly) into the 
959
 
    parent.
 
904
    This command only works on branches that have not diverged.  Branches are
 
905
    considered diverged if the destination branch's most recent commit is one
 
906
    that has not been merged (directly or indirectly) into the parent.
960
907
 
961
908
    If branches have diverged, you can use 'bzr merge' to integrate the changes
962
909
    from one into the other.  Once one branch has merged, the other should
963
910
    be able to pull it again.
964
911
 
965
 
    If you want to replace your local changes and just want your branch to
966
 
    match the remote one, use pull --overwrite. This will work even if the two
967
 
    branches have diverged.
 
912
    If you want to forget your local changes and just update your branch to
 
913
    match the remote one, use pull --overwrite.
968
914
 
969
 
    If there is no default location set, the first pull will set it (use
970
 
    --no-remember to avoid settting it). After that, you can omit the
971
 
    location to use the default.  To change the default, use --remember. The
972
 
    value will only be saved if the remote location can be accessed.
 
915
    If there is no default location set, the first pull will set it.  After
 
916
    that, you can omit the location to use the default.  To change the
 
917
    default, use --remember. The value will only be saved if the remote
 
918
    location can be accessed.
973
919
 
974
920
    Note: The location can be specified either in the form of a branch,
975
921
    or in the form of a path to a file containing a merge directive generated
980
926
    takes_options = ['remember', 'overwrite', 'revision',
981
927
        custom_help('verbose',
982
928
            help='Show logs of pulled revisions.'),
983
 
        custom_help('directory',
 
929
        Option('directory',
984
930
            help='Branch to pull into, '
985
 
                 'rather than the one containing the working directory.'),
 
931
                 'rather than the one containing the working directory.',
 
932
            short_name='d',
 
933
            type=unicode,
 
934
            ),
986
935
        Option('local',
987
936
            help="Perform a local pull in a bound "
988
937
                 "branch.  Local pulls are not applied to "
989
938
                 "the master branch."
990
939
            ),
991
 
        Option('show-base',
992
 
            help="Show base revision text in conflicts.")
993
940
        ]
994
941
    takes_args = ['location?']
995
942
    encoding_type = 'replace'
996
943
 
997
 
    def run(self, location=None, remember=None, overwrite=False,
 
944
    def run(self, location=None, remember=False, overwrite=False,
998
945
            revision=None, verbose=False,
999
 
            directory=None, local=False,
1000
 
            show_base=False):
 
946
            directory=None, local=False):
1001
947
        # FIXME: too much stuff is in the command class
1002
948
        revision_id = None
1003
949
        mergeable = None
1006
952
        try:
1007
953
            tree_to = WorkingTree.open_containing(directory)[0]
1008
954
            branch_to = tree_to.branch
1009
 
            self.add_cleanup(tree_to.lock_write().unlock)
1010
955
        except errors.NoWorkingTree:
1011
956
            tree_to = None
1012
957
            branch_to = Branch.open_containing(directory)[0]
1013
 
            self.add_cleanup(branch_to.lock_write().unlock)
1014
 
 
1015
 
        if tree_to is None and show_base:
1016
 
            raise errors.BzrCommandError("Need working tree for --show-base.")
1017
 
 
 
958
        
1018
959
        if local and not branch_to.get_bound_location():
1019
960
            raise errors.LocalRequiresBoundBranch()
1020
961
 
1050
991
        else:
1051
992
            branch_from = Branch.open(location,
1052
993
                possible_transports=possible_transports)
1053
 
            self.add_cleanup(branch_from.lock_read().unlock)
1054
 
            # Remembers if asked explicitly or no previous location is set
1055
 
            if (remember
1056
 
                or (remember is None and branch_to.get_parent() is None)):
 
994
 
 
995
            if branch_to.get_parent() is None or remember:
1057
996
                branch_to.set_parent(branch_from.base)
1058
997
 
1059
 
        if revision is not None:
1060
 
            revision_id = revision.as_revision_id(branch_from)
1061
 
 
1062
 
        if tree_to is not None:
1063
 
            view_info = _get_view_info_for_change_reporter(tree_to)
1064
 
            change_reporter = delta._ChangeReporter(
1065
 
                unversioned_filter=tree_to.is_ignored,
1066
 
                view_info=view_info)
1067
 
            result = tree_to.pull(
1068
 
                branch_from, overwrite, revision_id, change_reporter,
1069
 
                possible_transports=possible_transports, local=local,
1070
 
                show_base=show_base)
1071
 
        else:
1072
 
            result = branch_to.pull(
1073
 
                branch_from, overwrite, revision_id, local=local)
1074
 
 
1075
 
        result.report(self.outf)
1076
 
        if verbose and result.old_revid != result.new_revid:
1077
 
            log.show_branch_change(
1078
 
                branch_to, self.outf, result.old_revno,
1079
 
                result.old_revid)
1080
 
        if getattr(result, 'tag_conflicts', None):
1081
 
            return 1
1082
 
        else:
1083
 
            return 0
 
998
        if branch_from is not branch_to:
 
999
            branch_from.lock_read()
 
1000
        try:
 
1001
            if revision is not None:
 
1002
                revision_id = revision.as_revision_id(branch_from)
 
1003
 
 
1004
            branch_to.lock_write()
 
1005
            try:
 
1006
                if tree_to is not None:
 
1007
                    view_info = _get_view_info_for_change_reporter(tree_to)
 
1008
                    change_reporter = delta._ChangeReporter(
 
1009
                        unversioned_filter=tree_to.is_ignored,
 
1010
                        view_info=view_info)
 
1011
                    result = tree_to.pull(
 
1012
                        branch_from, overwrite, revision_id, change_reporter,
 
1013
                        possible_transports=possible_transports, local=local)
 
1014
                else:
 
1015
                    result = branch_to.pull(
 
1016
                        branch_from, overwrite, revision_id, local=local)
 
1017
 
 
1018
                result.report(self.outf)
 
1019
                if verbose and result.old_revid != result.new_revid:
 
1020
                    log.show_branch_change(
 
1021
                        branch_to, self.outf, result.old_revno,
 
1022
                        result.old_revid)
 
1023
            finally:
 
1024
                branch_to.unlock()
 
1025
        finally:
 
1026
            if branch_from is not branch_to:
 
1027
                branch_from.unlock()
1084
1028
 
1085
1029
 
1086
1030
class cmd_push(Command):
1087
 
    __doc__ = """Update a mirror of this branch.
 
1031
    """Update a mirror of this branch.
1088
1032
 
1089
1033
    The target branch will not have its working tree populated because this
1090
1034
    is both expensive, and is not supported on remote file systems.
1103
1047
    do a merge (see bzr help merge) from the other branch, and commit that.
1104
1048
    After that you will be able to do a push without '--overwrite'.
1105
1049
 
1106
 
    If there is no default push location set, the first push will set it (use
1107
 
    --no-remember to avoid settting it).  After that, you can omit the
1108
 
    location to use the default.  To change the default, use --remember. The
1109
 
    value will only be saved if the remote location can be accessed.
 
1050
    If there is no default push location set, the first push will set it.
 
1051
    After that, you can omit the location to use the default.  To change the
 
1052
    default, use --remember. The value will only be saved if the remote
 
1053
    location can be accessed.
1110
1054
    """
1111
1055
 
1112
1056
    _see_also = ['pull', 'update', 'working-trees']
1114
1058
        Option('create-prefix',
1115
1059
               help='Create the path leading up to the branch '
1116
1060
                    'if it does not already exist.'),
1117
 
        custom_help('directory',
 
1061
        Option('directory',
1118
1062
            help='Branch to push from, '
1119
 
                 'rather than the one containing the working directory.'),
 
1063
                 'rather than the one containing the working directory.',
 
1064
            short_name='d',
 
1065
            type=unicode,
 
1066
            ),
1120
1067
        Option('use-existing-dir',
1121
1068
               help='By default push will fail if the target'
1122
1069
                    ' directory exists, but does not already'
1133
1080
        Option('strict',
1134
1081
               help='Refuse to push if there are uncommitted changes in'
1135
1082
               ' the working tree, --no-strict disables the check.'),
1136
 
        Option('no-tree',
1137
 
               help="Don't populate the working tree, even for protocols"
1138
 
               " that support it."),
1139
1083
        ]
1140
1084
    takes_args = ['location?']
1141
1085
    encoding_type = 'replace'
1142
1086
 
1143
 
    def run(self, location=None, remember=None, overwrite=False,
 
1087
    def run(self, location=None, remember=False, overwrite=False,
1144
1088
        create_prefix=False, verbose=False, revision=None,
1145
1089
        use_existing_dir=False, directory=None, stacked_on=None,
1146
 
        stacked=False, strict=None, no_tree=False):
 
1090
        stacked=False, strict=None):
1147
1091
        from bzrlib.push import _show_push_branch
1148
1092
 
1149
1093
        if directory is None:
1151
1095
        # Get the source branch
1152
1096
        (tree, br_from,
1153
1097
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1098
        if strict is None:
 
1099
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
 
1100
        if strict is None: strict = True # default value
1154
1101
        # Get the tip's revision_id
1155
1102
        revision = _get_one_revision('push', revision)
1156
1103
        if revision is not None:
1157
1104
            revision_id = revision.in_history(br_from).rev_id
1158
1105
        else:
1159
1106
            revision_id = None
1160
 
        if tree is not None and revision_id is None:
1161
 
            tree.check_changed_or_out_of_date(
1162
 
                strict, 'push_strict',
1163
 
                more_error='Use --no-strict to force the push.',
1164
 
                more_warning='Uncommitted changes will not be pushed.')
 
1107
        if strict and tree is not None and revision_id is None:
 
1108
            if (tree.has_changes(tree.basis_tree())
 
1109
                or len(tree.get_parent_ids()) > 1):
 
1110
                raise errors.UncommittedChanges(
 
1111
                    tree, more='Use --no-strict to force the push.')
 
1112
            if tree.last_revision() != tree.branch.last_revision():
 
1113
                # The tree has lost sync with its branch, there is little
 
1114
                # chance that the user is aware of it but he can still force
 
1115
                # the push with --no-strict
 
1116
                raise errors.OutOfDateTree(
 
1117
                    tree, more='Use --no-strict to force the push.')
 
1118
 
1165
1119
        # Get the stacked_on branch, if any
1166
1120
        if stacked_on is not None:
1167
1121
            stacked_on = urlutils.normalize_url(stacked_on)
1195
1149
        _show_push_branch(br_from, revision_id, location, self.outf,
1196
1150
            verbose=verbose, overwrite=overwrite, remember=remember,
1197
1151
            stacked_on=stacked_on, create_prefix=create_prefix,
1198
 
            use_existing_dir=use_existing_dir, no_tree=no_tree)
 
1152
            use_existing_dir=use_existing_dir)
1199
1153
 
1200
1154
 
1201
1155
class cmd_branch(Command):
1202
 
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
1156
    """Create a new branch that is a copy of an existing branch.
1203
1157
 
1204
1158
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1205
1159
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1210
1164
 
1211
1165
    To retrieve the branch as of a particular revision, supply the --revision
1212
1166
    parameter, as in "branch foo/bar -r 5".
1213
 
 
1214
 
    The synonyms 'clone' and 'get' for this command are deprecated.
1215
1167
    """
1216
1168
 
1217
1169
    _see_also = ['checkout']
1218
1170
    takes_args = ['from_location', 'to_location?']
1219
 
    takes_options = ['revision',
1220
 
        Option('hardlink', help='Hard-link working tree files where possible.'),
1221
 
        Option('files-from', type=str,
1222
 
               help="Get file contents from this tree."),
 
1171
    takes_options = ['revision', Option('hardlink',
 
1172
        help='Hard-link working tree files where possible.'),
1223
1173
        Option('no-tree',
1224
1174
            help="Create a branch without a working-tree."),
1225
 
        Option('switch',
1226
 
            help="Switch the checkout in the current directory "
1227
 
                 "to the new branch."),
1228
1175
        Option('stacked',
1229
1176
            help='Create a stacked branch referring to the source branch. '
1230
1177
                'The new branch will depend on the availability of the source '
1236
1183
                    ' directory exists, but does not already'
1237
1184
                    ' have a control directory.  This flag will'
1238
1185
                    ' allow branch to proceed.'),
1239
 
        Option('bind',
1240
 
            help="Bind new branch to from location."),
1241
1186
        ]
1242
1187
    aliases = ['get', 'clone']
1243
1188
 
1244
1189
    def run(self, from_location, to_location=None, revision=None,
1245
1190
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1246
 
            use_existing_dir=False, switch=False, bind=False,
1247
 
            files_from=None):
1248
 
        from bzrlib import switch as _mod_switch
 
1191
            use_existing_dir=False):
1249
1192
        from bzrlib.tag import _merge_tags_if_possible
1250
 
        if self.invoked_as in ['get', 'clone']:
1251
 
            ui.ui_factory.show_user_warning(
1252
 
                'deprecated_command',
1253
 
                deprecated_name=self.invoked_as,
1254
 
                recommended_name='branch',
1255
 
                deprecated_in_version='2.4')
 
1193
 
1256
1194
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1257
1195
            from_location)
1258
 
        if not (hardlink or files_from):
1259
 
            # accelerator_tree is usually slower because you have to read N
1260
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1261
 
            # explicitly request it
 
1196
        if (accelerator_tree is not None and
 
1197
            accelerator_tree.supports_content_filtering()):
1262
1198
            accelerator_tree = None
1263
 
        if files_from is not None and files_from != from_location:
1264
 
            accelerator_tree = WorkingTree.open(files_from)
1265
1199
        revision = _get_one_revision('branch', revision)
1266
 
        self.add_cleanup(br_from.lock_read().unlock)
1267
 
        if revision is not None:
1268
 
            revision_id = revision.as_revision_id(br_from)
1269
 
        else:
1270
 
            # FIXME - wt.last_revision, fallback to branch, fall back to
1271
 
            # None or perhaps NULL_REVISION to mean copy nothing
1272
 
            # RBC 20060209
1273
 
            revision_id = br_from.last_revision()
1274
 
        if to_location is None:
1275
 
            to_location = urlutils.derive_to_location(from_location)
1276
 
        to_transport = transport.get_transport(to_location)
 
1200
        br_from.lock_read()
1277
1201
        try:
1278
 
            to_transport.mkdir('.')
1279
 
        except errors.FileExists:
1280
 
            if not use_existing_dir:
1281
 
                raise errors.BzrCommandError('Target directory "%s" '
1282
 
                    'already exists.' % to_location)
 
1202
            if revision is not None:
 
1203
                revision_id = revision.as_revision_id(br_from)
1283
1204
            else:
1284
 
                try:
1285
 
                    bzrdir.BzrDir.open_from_transport(to_transport)
1286
 
                except errors.NotBranchError:
1287
 
                    pass
 
1205
                # FIXME - wt.last_revision, fallback to branch, fall back to
 
1206
                # None or perhaps NULL_REVISION to mean copy nothing
 
1207
                # RBC 20060209
 
1208
                revision_id = br_from.last_revision()
 
1209
            if to_location is None:
 
1210
                to_location = urlutils.derive_to_location(from_location)
 
1211
            to_transport = transport.get_transport(to_location)
 
1212
            try:
 
1213
                to_transport.mkdir('.')
 
1214
            except errors.FileExists:
 
1215
                if not use_existing_dir:
 
1216
                    raise errors.BzrCommandError('Target directory "%s" '
 
1217
                        'already exists.' % to_location)
1288
1218
                else:
1289
 
                    raise errors.AlreadyBranchError(to_location)
1290
 
        except errors.NoSuchFile:
1291
 
            raise errors.BzrCommandError('Parent of "%s" does not exist.'
1292
 
                                         % to_location)
1293
 
        try:
1294
 
            # preserve whatever source format we have.
1295
 
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1296
 
                                        possible_transports=[to_transport],
1297
 
                                        accelerator_tree=accelerator_tree,
1298
 
                                        hardlink=hardlink, stacked=stacked,
1299
 
                                        force_new_repo=standalone,
1300
 
                                        create_tree_if_local=not no_tree,
1301
 
                                        source_branch=br_from)
1302
 
            branch = dir.open_branch()
1303
 
        except errors.NoSuchRevision:
1304
 
            to_transport.delete_tree('.')
1305
 
            msg = "The branch %s has no revision %s." % (from_location,
1306
 
                revision)
1307
 
            raise errors.BzrCommandError(msg)
1308
 
        _merge_tags_if_possible(br_from, branch)
1309
 
        # If the source branch is stacked, the new branch may
1310
 
        # be stacked whether we asked for that explicitly or not.
1311
 
        # We therefore need a try/except here and not just 'if stacked:'
1312
 
        try:
1313
 
            note('Created new stacked branch referring to %s.' %
1314
 
                branch.get_stacked_on_url())
1315
 
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1316
 
            errors.UnstackableRepositoryFormat), e:
1317
 
            note('Branched %d revision(s).' % branch.revno())
1318
 
        if bind:
1319
 
            # Bind to the parent
1320
 
            parent_branch = Branch.open(from_location)
1321
 
            branch.bind(parent_branch)
1322
 
            note('New branch bound to %s' % from_location)
1323
 
        if switch:
1324
 
            # Switch to the new branch
1325
 
            wt, _ = WorkingTree.open_containing('.')
1326
 
            _mod_switch.switch(wt.bzrdir, branch)
1327
 
            note('Switched to branch: %s',
1328
 
                urlutils.unescape_for_display(branch.base, 'utf-8'))
 
1219
                    try:
 
1220
                        bzrdir.BzrDir.open_from_transport(to_transport)
 
1221
                    except errors.NotBranchError:
 
1222
                        pass
 
1223
                    else:
 
1224
                        raise errors.AlreadyBranchError(to_location)
 
1225
            except errors.NoSuchFile:
 
1226
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
 
1227
                                             % to_location)
 
1228
            try:
 
1229
                # preserve whatever source format we have.
 
1230
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
1231
                                            possible_transports=[to_transport],
 
1232
                                            accelerator_tree=accelerator_tree,
 
1233
                                            hardlink=hardlink, stacked=stacked,
 
1234
                                            force_new_repo=standalone,
 
1235
                                            create_tree_if_local=not no_tree,
 
1236
                                            source_branch=br_from)
 
1237
                branch = dir.open_branch()
 
1238
            except errors.NoSuchRevision:
 
1239
                to_transport.delete_tree('.')
 
1240
                msg = "The branch %s has no revision %s." % (from_location,
 
1241
                    revision)
 
1242
                raise errors.BzrCommandError(msg)
 
1243
            _merge_tags_if_possible(br_from, branch)
 
1244
            # If the source branch is stacked, the new branch may
 
1245
            # be stacked whether we asked for that explicitly or not.
 
1246
            # We therefore need a try/except here and not just 'if stacked:'
 
1247
            try:
 
1248
                note('Created new stacked branch referring to %s.' %
 
1249
                    branch.get_stacked_on_url())
 
1250
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
1251
                errors.UnstackableRepositoryFormat), e:
 
1252
                note('Branched %d revision(s).' % branch.revno())
 
1253
        finally:
 
1254
            br_from.unlock()
1329
1255
 
1330
1256
 
1331
1257
class cmd_checkout(Command):
1332
 
    __doc__ = """Create a new checkout of an existing branch.
 
1258
    """Create a new checkout of an existing branch.
1333
1259
 
1334
1260
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1335
1261
    the branch found in '.'. This is useful if you have removed the working tree
1374
1300
            to_location = branch_location
1375
1301
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1376
1302
            branch_location)
1377
 
        if not (hardlink or files_from):
1378
 
            # accelerator_tree is usually slower because you have to read N
1379
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1380
 
            # explicitly request it
1381
 
            accelerator_tree = None
1382
1303
        revision = _get_one_revision('checkout', revision)
1383
 
        if files_from is not None and files_from != branch_location:
 
1304
        if files_from is not None:
1384
1305
            accelerator_tree = WorkingTree.open(files_from)
1385
1306
        if revision is not None:
1386
1307
            revision_id = revision.as_revision_id(source)
1403
1324
 
1404
1325
 
1405
1326
class cmd_renames(Command):
1406
 
    __doc__ = """Show list of renamed files.
 
1327
    """Show list of renamed files.
1407
1328
    """
1408
1329
    # TODO: Option to show renames between two historical versions.
1409
1330
 
1414
1335
    @display_command
1415
1336
    def run(self, dir=u'.'):
1416
1337
        tree = WorkingTree.open_containing(dir)[0]
1417
 
        self.add_cleanup(tree.lock_read().unlock)
1418
 
        new_inv = tree.inventory
1419
 
        old_tree = tree.basis_tree()
1420
 
        self.add_cleanup(old_tree.lock_read().unlock)
1421
 
        old_inv = old_tree.inventory
1422
 
        renames = []
1423
 
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1424
 
        for f, paths, c, v, p, n, k, e in iterator:
1425
 
            if paths[0] == paths[1]:
1426
 
                continue
1427
 
            if None in (paths):
1428
 
                continue
1429
 
            renames.append(paths)
1430
 
        renames.sort()
1431
 
        for old_name, new_name in renames:
1432
 
            self.outf.write("%s => %s\n" % (old_name, new_name))
 
1338
        tree.lock_read()
 
1339
        try:
 
1340
            new_inv = tree.inventory
 
1341
            old_tree = tree.basis_tree()
 
1342
            old_tree.lock_read()
 
1343
            try:
 
1344
                old_inv = old_tree.inventory
 
1345
                renames = []
 
1346
                iterator = tree.iter_changes(old_tree, include_unchanged=True)
 
1347
                for f, paths, c, v, p, n, k, e in iterator:
 
1348
                    if paths[0] == paths[1]:
 
1349
                        continue
 
1350
                    if None in (paths):
 
1351
                        continue
 
1352
                    renames.append(paths)
 
1353
                renames.sort()
 
1354
                for old_name, new_name in renames:
 
1355
                    self.outf.write("%s => %s\n" % (old_name, new_name))
 
1356
            finally:
 
1357
                old_tree.unlock()
 
1358
        finally:
 
1359
            tree.unlock()
1433
1360
 
1434
1361
 
1435
1362
class cmd_update(Command):
1436
 
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1363
    """Update a tree to have the latest code committed to its branch.
1437
1364
 
1438
1365
    This will perform a merge into the working tree, and may generate
1439
1366
    conflicts. If you have any local changes, you will still
1441
1368
 
1442
1369
    If you want to discard your local changes, you can just do a
1443
1370
    'bzr revert' instead of 'bzr commit' after the update.
1444
 
 
1445
 
    If you want to restore a file that has been removed locally, use
1446
 
    'bzr revert' instead of 'bzr update'.
1447
 
 
1448
 
    If the tree's branch is bound to a master branch, it will also update
1449
 
    the branch from the master.
1450
1371
    """
1451
1372
 
1452
1373
    _see_also = ['pull', 'working-trees', 'status-flags']
1453
1374
    takes_args = ['dir?']
1454
 
    takes_options = ['revision',
1455
 
                     Option('show-base',
1456
 
                            help="Show base revision text in conflicts."),
1457
 
                     ]
1458
1375
    aliases = ['up']
1459
1376
 
1460
 
    def run(self, dir='.', revision=None, show_base=None):
1461
 
        if revision is not None and len(revision) != 1:
1462
 
            raise errors.BzrCommandError(
1463
 
                        "bzr update --revision takes exactly one revision")
 
1377
    def run(self, dir='.'):
1464
1378
        tree = WorkingTree.open_containing(dir)[0]
1465
 
        branch = tree.branch
1466
1379
        possible_transports = []
1467
 
        master = branch.get_master_branch(
 
1380
        master = tree.branch.get_master_branch(
1468
1381
            possible_transports=possible_transports)
1469
1382
        if master is not None:
1470
 
            branch_location = master.base
1471
1383
            tree.lock_write()
1472
1384
        else:
1473
 
            branch_location = tree.branch.base
1474
1385
            tree.lock_tree_write()
1475
 
        self.add_cleanup(tree.unlock)
1476
 
        # get rid of the final '/' and be ready for display
1477
 
        branch_location = urlutils.unescape_for_display(
1478
 
            branch_location.rstrip('/'),
1479
 
            self.outf.encoding)
1480
 
        existing_pending_merges = tree.get_parent_ids()[1:]
1481
 
        if master is None:
1482
 
            old_tip = None
1483
 
        else:
1484
 
            # may need to fetch data into a heavyweight checkout
1485
 
            # XXX: this may take some time, maybe we should display a
1486
 
            # message
1487
 
            old_tip = branch.update(possible_transports)
1488
 
        if revision is not None:
1489
 
            revision_id = revision[0].as_revision_id(branch)
1490
 
        else:
1491
 
            revision_id = branch.last_revision()
1492
 
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1493
 
            revno = branch.revision_id_to_dotted_revno(revision_id)
1494
 
            note("Tree is up to date at revision %s of branch %s" %
1495
 
                ('.'.join(map(str, revno)), branch_location))
1496
 
            return 0
1497
 
        view_info = _get_view_info_for_change_reporter(tree)
1498
 
        change_reporter = delta._ChangeReporter(
1499
 
            unversioned_filter=tree.is_ignored,
1500
 
            view_info=view_info)
1501
1386
        try:
 
1387
            existing_pending_merges = tree.get_parent_ids()[1:]
 
1388
            last_rev = _mod_revision.ensure_null(tree.last_revision())
 
1389
            if last_rev == _mod_revision.ensure_null(
 
1390
                tree.branch.last_revision()):
 
1391
                # may be up to date, check master too.
 
1392
                if master is None or last_rev == _mod_revision.ensure_null(
 
1393
                    master.last_revision()):
 
1394
                    revno = tree.branch.revision_id_to_revno(last_rev)
 
1395
                    note("Tree is up to date at revision %d." % (revno,))
 
1396
                    return 0
 
1397
            view_info = _get_view_info_for_change_reporter(tree)
1502
1398
            conflicts = tree.update(
1503
 
                change_reporter,
1504
 
                possible_transports=possible_transports,
1505
 
                revision=revision_id,
1506
 
                old_tip=old_tip,
1507
 
                show_base=show_base)
1508
 
        except errors.NoSuchRevision, e:
1509
 
            raise errors.BzrCommandError(
1510
 
                                  "branch has no revision %s\n"
1511
 
                                  "bzr update --revision only works"
1512
 
                                  " for a revision in the branch history"
1513
 
                                  % (e.revision))
1514
 
        revno = tree.branch.revision_id_to_dotted_revno(
1515
 
            _mod_revision.ensure_null(tree.last_revision()))
1516
 
        note('Updated to revision %s of branch %s' %
1517
 
             ('.'.join(map(str, revno)), branch_location))
1518
 
        parent_ids = tree.get_parent_ids()
1519
 
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1520
 
            note('Your local commits will now show as pending merges with '
1521
 
                 "'bzr status', and can be committed with 'bzr commit'.")
1522
 
        if conflicts != 0:
1523
 
            return 1
1524
 
        else:
1525
 
            return 0
 
1399
                delta._ChangeReporter(unversioned_filter=tree.is_ignored,
 
1400
                view_info=view_info), possible_transports=possible_transports)
 
1401
            revno = tree.branch.revision_id_to_revno(
 
1402
                _mod_revision.ensure_null(tree.last_revision()))
 
1403
            note('Updated to revision %d.' % (revno,))
 
1404
            if tree.get_parent_ids()[1:] != existing_pending_merges:
 
1405
                note('Your local commits will now show as pending merges with '
 
1406
                     "'bzr status', and can be committed with 'bzr commit'.")
 
1407
            if conflicts != 0:
 
1408
                return 1
 
1409
            else:
 
1410
                return 0
 
1411
        finally:
 
1412
            tree.unlock()
1526
1413
 
1527
1414
 
1528
1415
class cmd_info(Command):
1529
 
    __doc__ = """Show information about a working tree, branch or repository.
 
1416
    """Show information about a working tree, branch or repository.
1530
1417
 
1531
1418
    This command will show all known locations and formats associated to the
1532
1419
    tree, branch or repository.
1570
1457
 
1571
1458
 
1572
1459
class cmd_remove(Command):
1573
 
    __doc__ = """Remove files or directories.
 
1460
    """Remove files or directories.
1574
1461
 
1575
 
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1576
 
    delete them if they can easily be recovered using revert otherwise they
1577
 
    will be backed up (adding an extention of the form .~#~). If no options or
1578
 
    parameters are given Bazaar will scan for files that are being tracked by
1579
 
    Bazaar but missing in your tree and stop tracking them for you.
 
1462
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1463
    them if they can easily be recovered using revert. If no options or
 
1464
    parameters are given bzr will scan for files that are being tracked by bzr
 
1465
    but missing in your tree and stop tracking them for you.
1580
1466
    """
1581
1467
    takes_args = ['file*']
1582
1468
    takes_options = ['verbose',
1584
1470
        RegistryOption.from_kwargs('file-deletion-strategy',
1585
1471
            'The file deletion mode to be used.',
1586
1472
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1587
 
            safe='Backup changed files (default).',
 
1473
            safe='Only delete files if they can be'
 
1474
                 ' safely recovered (default).',
1588
1475
            keep='Delete from bzr but leave the working copy.',
1589
 
            no_backup='Don\'t backup changed files.',
1590
1476
            force='Delete all the specified files, even if they can not be '
1591
 
                'recovered and even if they are non-empty directories. '
1592
 
                '(deprecated, use no-backup)')]
 
1477
                'recovered and even if they are non-empty directories.')]
1593
1478
    aliases = ['rm', 'del']
1594
1479
    encoding_type = 'replace'
1595
1480
 
1596
1481
    def run(self, file_list, verbose=False, new=False,
1597
1482
        file_deletion_strategy='safe'):
1598
 
        if file_deletion_strategy == 'force':
1599
 
            note("(The --force option is deprecated, rather use --no-backup "
1600
 
                "in future.)")
1601
 
            file_deletion_strategy = 'no-backup'
1602
 
 
1603
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1483
        tree, file_list = tree_files(file_list)
1604
1484
 
1605
1485
        if file_list is not None:
1606
1486
            file_list = [f for f in file_list]
1607
1487
 
1608
 
        self.add_cleanup(tree.lock_write().unlock)
1609
 
        # Heuristics should probably all move into tree.remove_smart or
1610
 
        # some such?
1611
 
        if new:
1612
 
            added = tree.changes_from(tree.basis_tree(),
1613
 
                specific_files=file_list).added
1614
 
            file_list = sorted([f[0] for f in added], reverse=True)
1615
 
            if len(file_list) == 0:
1616
 
                raise errors.BzrCommandError('No matching files.')
1617
 
        elif file_list is None:
1618
 
            # missing files show up in iter_changes(basis) as
1619
 
            # versioned-with-no-kind.
1620
 
            missing = []
1621
 
            for change in tree.iter_changes(tree.basis_tree()):
1622
 
                # Find paths in the working tree that have no kind:
1623
 
                if change[1][1] is not None and change[6][1] is None:
1624
 
                    missing.append(change[1][1])
1625
 
            file_list = sorted(missing, reverse=True)
1626
 
            file_deletion_strategy = 'keep'
1627
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1628
 
            keep_files=file_deletion_strategy=='keep',
1629
 
            force=(file_deletion_strategy=='no-backup'))
 
1488
        tree.lock_write()
 
1489
        try:
 
1490
            # Heuristics should probably all move into tree.remove_smart or
 
1491
            # some such?
 
1492
            if new:
 
1493
                added = tree.changes_from(tree.basis_tree(),
 
1494
                    specific_files=file_list).added
 
1495
                file_list = sorted([f[0] for f in added], reverse=True)
 
1496
                if len(file_list) == 0:
 
1497
                    raise errors.BzrCommandError('No matching files.')
 
1498
            elif file_list is None:
 
1499
                # missing files show up in iter_changes(basis) as
 
1500
                # versioned-with-no-kind.
 
1501
                missing = []
 
1502
                for change in tree.iter_changes(tree.basis_tree()):
 
1503
                    # Find paths in the working tree that have no kind:
 
1504
                    if change[1][1] is not None and change[6][1] is None:
 
1505
                        missing.append(change[1][1])
 
1506
                file_list = sorted(missing, reverse=True)
 
1507
                file_deletion_strategy = 'keep'
 
1508
            tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1509
                keep_files=file_deletion_strategy=='keep',
 
1510
                force=file_deletion_strategy=='force')
 
1511
        finally:
 
1512
            tree.unlock()
1630
1513
 
1631
1514
 
1632
1515
class cmd_file_id(Command):
1633
 
    __doc__ = """Print file_id of a particular file or directory.
 
1516
    """Print file_id of a particular file or directory.
1634
1517
 
1635
1518
    The file_id is assigned when the file is first added and remains the
1636
1519
    same through all revisions where the file exists, even when it is
1652
1535
 
1653
1536
 
1654
1537
class cmd_file_path(Command):
1655
 
    __doc__ = """Print path of file_ids to a file or directory.
 
1538
    """Print path of file_ids to a file or directory.
1656
1539
 
1657
1540
    This prints one line for each directory down to the target,
1658
1541
    starting at the branch root.
1674
1557
 
1675
1558
 
1676
1559
class cmd_reconcile(Command):
1677
 
    __doc__ = """Reconcile bzr metadata in a branch.
 
1560
    """Reconcile bzr metadata in a branch.
1678
1561
 
1679
1562
    This can correct data mismatches that may have been caused by
1680
1563
    previous ghost operations or bzr upgrades. You should only
1694
1577
 
1695
1578
    _see_also = ['check']
1696
1579
    takes_args = ['branch?']
1697
 
    takes_options = [
1698
 
        Option('canonicalize-chks',
1699
 
               help='Make sure CHKs are in canonical form (repairs '
1700
 
                    'bug 522637).',
1701
 
               hidden=True),
1702
 
        ]
1703
1580
 
1704
 
    def run(self, branch=".", canonicalize_chks=False):
 
1581
    def run(self, branch="."):
1705
1582
        from bzrlib.reconcile import reconcile
1706
1583
        dir = bzrdir.BzrDir.open(branch)
1707
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1584
        reconcile(dir)
1708
1585
 
1709
1586
 
1710
1587
class cmd_revision_history(Command):
1711
 
    __doc__ = """Display the list of revision ids on a branch."""
 
1588
    """Display the list of revision ids on a branch."""
1712
1589
 
1713
1590
    _see_also = ['log']
1714
1591
    takes_args = ['location?']
1724
1601
 
1725
1602
 
1726
1603
class cmd_ancestry(Command):
1727
 
    __doc__ = """List all revisions merged into this branch."""
 
1604
    """List all revisions merged into this branch."""
1728
1605
 
1729
1606
    _see_also = ['log', 'revision-history']
1730
1607
    takes_args = ['location?']
1742
1619
            b = wt.branch
1743
1620
            last_revision = wt.last_revision()
1744
1621
 
1745
 
        self.add_cleanup(b.repository.lock_read().unlock)
1746
 
        graph = b.repository.get_graph()
1747
 
        revisions = [revid for revid, parents in
1748
 
            graph.iter_ancestry([last_revision])]
1749
 
        for revision_id in reversed(revisions):
1750
 
            if _mod_revision.is_null(revision_id):
1751
 
                continue
 
1622
        revision_ids = b.repository.get_ancestry(last_revision)
 
1623
        revision_ids.pop(0)
 
1624
        for revision_id in revision_ids:
1752
1625
            self.outf.write(revision_id + '\n')
1753
1626
 
1754
1627
 
1755
1628
class cmd_init(Command):
1756
 
    __doc__ = """Make a directory into a versioned branch.
 
1629
    """Make a directory into a versioned branch.
1757
1630
 
1758
1631
    Use this to create an empty branch, or before importing an
1759
1632
    existing project.
1787
1660
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1788
1661
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1789
1662
                value_switches=True,
1790
 
                title="Branch format",
 
1663
                title="Branch Format",
1791
1664
                ),
1792
1665
         Option('append-revisions-only',
1793
1666
                help='Never change revnos or the existing log.'
1794
 
                '  Append revisions to it only.'),
1795
 
         Option('no-tree',
1796
 
                'Create a branch without a working tree.')
 
1667
                '  Append revisions to it only.')
1797
1668
         ]
1798
1669
    def run(self, location=None, format=None, append_revisions_only=False,
1799
 
            create_prefix=False, no_tree=False):
 
1670
            create_prefix=False):
1800
1671
        if format is None:
1801
1672
            format = bzrdir.format_registry.make_bzrdir('default')
1802
1673
        if location is None:
1825
1696
        except errors.NotBranchError:
1826
1697
            # really a NotBzrDir error...
1827
1698
            create_branch = bzrdir.BzrDir.create_branch_convenience
1828
 
            if no_tree:
1829
 
                force_new_tree = False
1830
 
            else:
1831
 
                force_new_tree = None
1832
1699
            branch = create_branch(to_transport.base, format=format,
1833
 
                                   possible_transports=[to_transport],
1834
 
                                   force_new_tree=force_new_tree)
 
1700
                                   possible_transports=[to_transport])
1835
1701
            a_bzrdir = branch.bzrdir
1836
1702
        else:
1837
1703
            from bzrlib.transport.local import LocalTransport
1841
1707
                        raise errors.BranchExistsWithoutWorkingTree(location)
1842
1708
                raise errors.AlreadyBranchError(location)
1843
1709
            branch = a_bzrdir.create_branch()
1844
 
            if not no_tree:
1845
 
                a_bzrdir.create_workingtree()
 
1710
            a_bzrdir.create_workingtree()
1846
1711
        if append_revisions_only:
1847
1712
            try:
1848
1713
                branch.set_append_revisions_only(True)
1870
1735
 
1871
1736
 
1872
1737
class cmd_init_repository(Command):
1873
 
    __doc__ = """Create a shared repository for branches to share storage space.
 
1738
    """Create a shared repository to hold branches.
1874
1739
 
1875
1740
    New branches created under the repository directory will store their
1876
 
    revisions in the repository, not in the branch directory.  For branches
1877
 
    with shared history, this reduces the amount of storage needed and 
1878
 
    speeds up the creation of new branches.
 
1741
    revisions in the repository, not in the branch directory.
1879
1742
 
1880
 
    If the --no-trees option is given then the branches in the repository
1881
 
    will not have working trees by default.  They will still exist as 
1882
 
    directories on disk, but they will not have separate copies of the 
1883
 
    files at a certain revision.  This can be useful for repositories that
1884
 
    store branches which are interacted with through checkouts or remote
1885
 
    branches, such as on a server.
 
1743
    If the --no-trees option is used then the branches in the repository
 
1744
    will not have working trees by default.
1886
1745
 
1887
1746
    :Examples:
1888
 
        Create a shared repository holding just branches::
 
1747
        Create a shared repositories holding just branches::
1889
1748
 
1890
1749
            bzr init-repo --no-trees repo
1891
1750
            bzr init repo/trunk
1930
1789
 
1931
1790
 
1932
1791
class cmd_diff(Command):
1933
 
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1792
    """Show differences in the working tree, between revisions or branches.
1934
1793
 
1935
1794
    If no arguments are given, all changes for the current tree are listed.
1936
1795
    If files are given, only the changes in those files are listed.
1942
1801
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1943
1802
    produces patches suitable for "patch -p1".
1944
1803
 
1945
 
    Note that when using the -r argument with a range of revisions, the
1946
 
    differences are computed between the two specified revisions.  That
1947
 
    is, the command does not show the changes introduced by the first 
1948
 
    revision in the range.  This differs from the interpretation of 
1949
 
    revision ranges used by "bzr log" which includes the first revision
1950
 
    in the range.
1951
 
 
1952
1804
    :Exit values:
1953
1805
        1 - changed
1954
1806
        2 - unrepresentable changes
1964
1816
 
1965
1817
            bzr diff -r1
1966
1818
 
1967
 
        Difference between revision 3 and revision 1::
1968
 
 
1969
 
            bzr diff -r1..3
1970
 
 
1971
 
        Difference between revision 3 and revision 1 for branch xxx::
1972
 
 
1973
 
            bzr diff -r1..3 xxx
1974
 
 
1975
 
        The changes introduced by revision 2 (equivalent to -r1..2)::
1976
 
 
1977
 
            bzr diff -c2
1978
 
 
1979
 
        To see the changes introduced by revision X::
1980
 
        
1981
 
            bzr diff -cX
1982
 
 
1983
 
        Note that in the case of a merge, the -c option shows the changes
1984
 
        compared to the left hand parent. To see the changes against
1985
 
        another parent, use::
1986
 
 
1987
 
            bzr diff -r<chosen_parent>..X
1988
 
 
1989
 
        The changes between the current revision and the previous revision
1990
 
        (equivalent to -c-1 and -r-2..-1)
1991
 
 
1992
 
            bzr diff -r-2..
 
1819
        Difference between revision 2 and revision 1::
 
1820
 
 
1821
            bzr diff -r1..2
 
1822
 
 
1823
        Difference between revision 2 and revision 1 for branch xxx::
 
1824
 
 
1825
            bzr diff -r1..2 xxx
1993
1826
 
1994
1827
        Show just the differences for file NEWS::
1995
1828
 
2010
1843
        Same as 'bzr diff' but prefix paths with old/ and new/::
2011
1844
 
2012
1845
            bzr diff --prefix old/:new/
2013
 
            
2014
 
        Show the differences using a custom diff program with options::
2015
 
        
2016
 
            bzr diff --using /usr/bin/diff --diff-options -wu
2017
1846
    """
2018
1847
    _see_also = ['status']
2019
1848
    takes_args = ['file*']
2038
1867
            help='Use this command to compare files.',
2039
1868
            type=unicode,
2040
1869
            ),
2041
 
        RegistryOption('format',
2042
 
            short_name='F',
2043
 
            help='Diff format to use.',
2044
 
            lazy_registry=('bzrlib.diff', 'format_registry'),
2045
 
            title='Diff format'),
2046
1870
        ]
2047
1871
    aliases = ['di', 'dif']
2048
1872
    encoding_type = 'exact'
2049
1873
 
2050
1874
    @display_command
2051
1875
    def run(self, revision=None, file_list=None, diff_options=None,
2052
 
            prefix=None, old=None, new=None, using=None, format=None):
2053
 
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
2054
 
            show_diff_trees)
 
1876
            prefix=None, old=None, new=None, using=None):
 
1877
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
2055
1878
 
2056
1879
        if (prefix is None) or (prefix == '0'):
2057
1880
            # diff -p0 format
2071
1894
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
2072
1895
                                         ' one or two revision specifiers')
2073
1896
 
2074
 
        if using is not None and format is not None:
2075
 
            raise errors.BzrCommandError('--using and --format are mutually '
2076
 
                'exclusive.')
2077
 
 
2078
 
        (old_tree, new_tree,
2079
 
         old_branch, new_branch,
2080
 
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
2081
 
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
2082
 
        # GNU diff on Windows uses ANSI encoding for filenames
2083
 
        path_encoding = osutils.get_diff_header_encoding()
 
1897
        old_tree, new_tree, specific_files, extra_trees = \
 
1898
                _get_trees_to_diff(file_list, revision, old, new,
 
1899
                apply_view=True)
2084
1900
        return show_diff_trees(old_tree, new_tree, sys.stdout,
2085
1901
                               specific_files=specific_files,
2086
1902
                               external_diff_options=diff_options,
2087
1903
                               old_label=old_label, new_label=new_label,
2088
 
                               extra_trees=extra_trees,
2089
 
                               path_encoding=path_encoding,
2090
 
                               using=using,
2091
 
                               format_cls=format)
 
1904
                               extra_trees=extra_trees, using=using)
2092
1905
 
2093
1906
 
2094
1907
class cmd_deleted(Command):
2095
 
    __doc__ = """List files deleted in the working tree.
 
1908
    """List files deleted in the working tree.
2096
1909
    """
2097
1910
    # TODO: Show files deleted since a previous revision, or
2098
1911
    # between two revisions.
2101
1914
    # level of effort but possibly much less IO.  (Or possibly not,
2102
1915
    # if the directories are very large...)
2103
1916
    _see_also = ['status', 'ls']
2104
 
    takes_options = ['directory', 'show-ids']
 
1917
    takes_options = ['show-ids']
2105
1918
 
2106
1919
    @display_command
2107
 
    def run(self, show_ids=False, directory=u'.'):
2108
 
        tree = WorkingTree.open_containing(directory)[0]
2109
 
        self.add_cleanup(tree.lock_read().unlock)
2110
 
        old = tree.basis_tree()
2111
 
        self.add_cleanup(old.lock_read().unlock)
2112
 
        for path, ie in old.inventory.iter_entries():
2113
 
            if not tree.has_id(ie.file_id):
2114
 
                self.outf.write(path)
2115
 
                if show_ids:
2116
 
                    self.outf.write(' ')
2117
 
                    self.outf.write(ie.file_id)
2118
 
                self.outf.write('\n')
 
1920
    def run(self, show_ids=False):
 
1921
        tree = WorkingTree.open_containing(u'.')[0]
 
1922
        tree.lock_read()
 
1923
        try:
 
1924
            old = tree.basis_tree()
 
1925
            old.lock_read()
 
1926
            try:
 
1927
                for path, ie in old.inventory.iter_entries():
 
1928
                    if not tree.has_id(ie.file_id):
 
1929
                        self.outf.write(path)
 
1930
                        if show_ids:
 
1931
                            self.outf.write(' ')
 
1932
                            self.outf.write(ie.file_id)
 
1933
                        self.outf.write('\n')
 
1934
            finally:
 
1935
                old.unlock()
 
1936
        finally:
 
1937
            tree.unlock()
2119
1938
 
2120
1939
 
2121
1940
class cmd_modified(Command):
2122
 
    __doc__ = """List files modified in working tree.
 
1941
    """List files modified in working tree.
2123
1942
    """
2124
1943
 
2125
1944
    hidden = True
2126
1945
    _see_also = ['status', 'ls']
2127
 
    takes_options = ['directory', 'null']
 
1946
    takes_options = [
 
1947
            Option('null',
 
1948
                   help='Write an ascii NUL (\\0) separator '
 
1949
                   'between files rather than a newline.')
 
1950
            ]
2128
1951
 
2129
1952
    @display_command
2130
 
    def run(self, null=False, directory=u'.'):
2131
 
        tree = WorkingTree.open_containing(directory)[0]
2132
 
        self.add_cleanup(tree.lock_read().unlock)
 
1953
    def run(self, null=False):
 
1954
        tree = WorkingTree.open_containing(u'.')[0]
2133
1955
        td = tree.changes_from(tree.basis_tree())
2134
 
        self.cleanup_now()
2135
1956
        for path, id, kind, text_modified, meta_modified in td.modified:
2136
1957
            if null:
2137
1958
                self.outf.write(path + '\0')
2140
1961
 
2141
1962
 
2142
1963
class cmd_added(Command):
2143
 
    __doc__ = """List files added in working tree.
 
1964
    """List files added in working tree.
2144
1965
    """
2145
1966
 
2146
1967
    hidden = True
2147
1968
    _see_also = ['status', 'ls']
2148
 
    takes_options = ['directory', 'null']
 
1969
    takes_options = [
 
1970
            Option('null',
 
1971
                   help='Write an ascii NUL (\\0) separator '
 
1972
                   'between files rather than a newline.')
 
1973
            ]
2149
1974
 
2150
1975
    @display_command
2151
 
    def run(self, null=False, directory=u'.'):
2152
 
        wt = WorkingTree.open_containing(directory)[0]
2153
 
        self.add_cleanup(wt.lock_read().unlock)
2154
 
        basis = wt.basis_tree()
2155
 
        self.add_cleanup(basis.lock_read().unlock)
2156
 
        basis_inv = basis.inventory
2157
 
        inv = wt.inventory
2158
 
        for file_id in inv:
2159
 
            if basis_inv.has_id(file_id):
2160
 
                continue
2161
 
            if inv.is_root(file_id) and len(basis_inv) == 0:
2162
 
                continue
2163
 
            path = inv.id2path(file_id)
2164
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2165
 
                continue
2166
 
            if null:
2167
 
                self.outf.write(path + '\0')
2168
 
            else:
2169
 
                self.outf.write(osutils.quotefn(path) + '\n')
 
1976
    def run(self, null=False):
 
1977
        wt = WorkingTree.open_containing(u'.')[0]
 
1978
        wt.lock_read()
 
1979
        try:
 
1980
            basis = wt.basis_tree()
 
1981
            basis.lock_read()
 
1982
            try:
 
1983
                basis_inv = basis.inventory
 
1984
                inv = wt.inventory
 
1985
                for file_id in inv:
 
1986
                    if file_id in basis_inv:
 
1987
                        continue
 
1988
                    if inv.is_root(file_id) and len(basis_inv) == 0:
 
1989
                        continue
 
1990
                    path = inv.id2path(file_id)
 
1991
                    if not os.access(osutils.abspath(path), os.F_OK):
 
1992
                        continue
 
1993
                    if null:
 
1994
                        self.outf.write(path + '\0')
 
1995
                    else:
 
1996
                        self.outf.write(osutils.quotefn(path) + '\n')
 
1997
            finally:
 
1998
                basis.unlock()
 
1999
        finally:
 
2000
            wt.unlock()
2170
2001
 
2171
2002
 
2172
2003
class cmd_root(Command):
2173
 
    __doc__ = """Show the tree root directory.
 
2004
    """Show the tree root directory.
2174
2005
 
2175
2006
    The root is the nearest enclosing directory with a .bzr control
2176
2007
    directory."""
2200
2031
 
2201
2032
 
2202
2033
class cmd_log(Command):
2203
 
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2034
    """Show historical log for a branch or subset of a branch.
2204
2035
 
2205
2036
    log is bzr's default tool for exploring the history of a branch.
2206
2037
    The branch to use is taken from the first parameter. If no parameters
2317
2148
    :Tips & tricks:
2318
2149
 
2319
2150
      GUI tools and IDEs are often better at exploring history than command
2320
 
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2321
 
      bzr-explorer shell, or the Loggerhead web interface.  See the Plugin
2322
 
      Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2323
 
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
 
2151
      line tools. You may prefer qlog or glog from the QBzr and Bzr-Gtk packages
 
2152
      respectively for example. (TortoiseBzr uses qlog for displaying logs.) See
 
2153
      http://bazaar-vcs.org/BzrPlugins and http://bazaar-vcs.org/IDEIntegration.
 
2154
 
 
2155
      Web interfaces are often better at exploring history than command line
 
2156
      tools, particularly for branches on servers. You may prefer Loggerhead
 
2157
      or one of its alternatives. See http://bazaar-vcs.org/WebInterface.
2324
2158
 
2325
2159
      You may find it useful to add the aliases below to ``bazaar.conf``::
2326
2160
 
2367
2201
                   help='Show just the specified revision.'
2368
2202
                   ' See also "help revisionspec".'),
2369
2203
            'log-format',
2370
 
            RegistryOption('authors',
2371
 
                'What names to list as authors - first, all or committer.',
2372
 
                title='Authors',
2373
 
                lazy_registry=('bzrlib.log', 'author_list_registry'),
2374
 
            ),
2375
2204
            Option('levels',
2376
2205
                   short_name='n',
2377
2206
                   help='Number of levels to display - 0 for all, 1 for flat.',
2392
2221
                   help='Show changes made in each revision as a patch.'),
2393
2222
            Option('include-merges',
2394
2223
                   help='Show merged revisions like --levels 0 does.'),
2395
 
            Option('exclude-common-ancestry',
2396
 
                   help='Display only the revisions that are not part'
2397
 
                   ' of both ancestries (require -rX..Y)'
2398
 
                   ),
2399
 
            Option('signatures',
2400
 
                   help='Show digital signature validity'),
2401
2224
            ]
2402
2225
    encoding_type = 'replace'
2403
2226
 
2413
2236
            message=None,
2414
2237
            limit=None,
2415
2238
            show_diff=False,
2416
 
            include_merges=False,
2417
 
            authors=None,
2418
 
            exclude_common_ancestry=False,
2419
 
            signatures=False,
2420
 
            ):
 
2239
            include_merges=False):
2421
2240
        from bzrlib.log import (
2422
2241
            Logger,
2423
2242
            make_log_request_dict,
2424
2243
            _get_info_for_log_files,
2425
2244
            )
2426
2245
        direction = (forward and 'forward') or 'reverse'
2427
 
        if (exclude_common_ancestry
2428
 
            and (revision is None or len(revision) != 2)):
2429
 
            raise errors.BzrCommandError(
2430
 
                '--exclude-common-ancestry requires -r with two revisions')
2431
2246
        if include_merges:
2432
2247
            if levels is None:
2433
2248
                levels = 0
2448
2263
        filter_by_dir = False
2449
2264
        if file_list:
2450
2265
            # find the file ids to log and check for directory filtering
2451
 
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2452
 
                revision, file_list, self.add_cleanup)
 
2266
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(revision,
 
2267
                file_list)
2453
2268
            for relpath, file_id, kind in file_info_list:
2454
2269
                if file_id is None:
2455
2270
                    raise errors.BzrCommandError(
2473
2288
                location = '.'
2474
2289
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2475
2290
            b = dir.open_branch()
2476
 
            self.add_cleanup(b.lock_read().unlock)
2477
2291
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2478
2292
 
2479
 
        if b.get_config().validate_signatures_in_log():
2480
 
            signatures = True
2481
 
 
2482
 
        if signatures:
2483
 
            if not gpg.GPGStrategy.verify_signatures_available():
2484
 
                raise errors.GpgmeNotInstalled(None)
2485
 
 
2486
2293
        # Decide on the type of delta & diff filtering to use
2487
2294
        # TODO: add an --all-files option to make this configurable & consistent
2488
2295
        if not verbose:
2496
2303
        else:
2497
2304
            diff_type = 'full'
2498
2305
 
2499
 
        # Build the log formatter
2500
 
        if log_format is None:
2501
 
            log_format = log.log_formatter_registry.get_default(b)
2502
 
        # Make a non-encoding output to include the diffs - bug 328007
2503
 
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2504
 
        lf = log_format(show_ids=show_ids, to_file=self.outf,
2505
 
                        to_exact_file=unencoded_output,
2506
 
                        show_timezone=timezone,
2507
 
                        delta_format=get_verbosity_level(),
2508
 
                        levels=levels,
2509
 
                        show_advice=levels is None,
2510
 
                        author_list_handler=authors)
2511
 
 
2512
 
        # Choose the algorithm for doing the logging. It's annoying
2513
 
        # having multiple code paths like this but necessary until
2514
 
        # the underlying repository format is faster at generating
2515
 
        # deltas or can provide everything we need from the indices.
2516
 
        # The default algorithm - match-using-deltas - works for
2517
 
        # multiple files and directories and is faster for small
2518
 
        # amounts of history (200 revisions say). However, it's too
2519
 
        # slow for logging a single file in a repository with deep
2520
 
        # history, i.e. > 10K revisions. In the spirit of "do no
2521
 
        # evil when adding features", we continue to use the
2522
 
        # original algorithm - per-file-graph - for the "single
2523
 
        # file that isn't a directory without showing a delta" case.
2524
 
        partial_history = revision and b.repository._format.supports_chks
2525
 
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2526
 
            or delta_type or partial_history)
2527
 
 
2528
 
        # Build the LogRequest and execute it
2529
 
        if len(file_ids) == 0:
2530
 
            file_ids = None
2531
 
        rqst = make_log_request_dict(
2532
 
            direction=direction, specific_fileids=file_ids,
2533
 
            start_revision=rev1, end_revision=rev2, limit=limit,
2534
 
            message_search=message, delta_type=delta_type,
2535
 
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2536
 
            exclude_common_ancestry=exclude_common_ancestry,
2537
 
            signature=signatures
2538
 
            )
2539
 
        Logger(b, rqst).show(lf)
 
2306
        b.lock_read()
 
2307
        try:
 
2308
            # Build the log formatter
 
2309
            if log_format is None:
 
2310
                log_format = log.log_formatter_registry.get_default(b)
 
2311
            lf = log_format(show_ids=show_ids, to_file=self.outf,
 
2312
                            show_timezone=timezone,
 
2313
                            delta_format=get_verbosity_level(),
 
2314
                            levels=levels,
 
2315
                            show_advice=levels is None)
 
2316
 
 
2317
            # Choose the algorithm for doing the logging. It's annoying
 
2318
            # having multiple code paths like this but necessary until
 
2319
            # the underlying repository format is faster at generating
 
2320
            # deltas or can provide everything we need from the indices.
 
2321
            # The default algorithm - match-using-deltas - works for
 
2322
            # multiple files and directories and is faster for small
 
2323
            # amounts of history (200 revisions say). However, it's too
 
2324
            # slow for logging a single file in a repository with deep
 
2325
            # history, i.e. > 10K revisions. In the spirit of "do no
 
2326
            # evil when adding features", we continue to use the
 
2327
            # original algorithm - per-file-graph - for the "single
 
2328
            # file that isn't a directory without showing a delta" case.
 
2329
            partial_history = revision and b.repository._format.supports_chks
 
2330
            match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2331
                or delta_type or partial_history)
 
2332
 
 
2333
            # Build the LogRequest and execute it
 
2334
            if len(file_ids) == 0:
 
2335
                file_ids = None
 
2336
            rqst = make_log_request_dict(
 
2337
                direction=direction, specific_fileids=file_ids,
 
2338
                start_revision=rev1, end_revision=rev2, limit=limit,
 
2339
                message_search=message, delta_type=delta_type,
 
2340
                diff_type=diff_type, _match_using_deltas=match_using_deltas)
 
2341
            Logger(b, rqst).show(lf)
 
2342
        finally:
 
2343
            b.unlock()
2540
2344
 
2541
2345
 
2542
2346
def _get_revision_range(revisionspec_list, branch, command_name):
2560
2364
            raise errors.BzrCommandError(
2561
2365
                "bzr %s doesn't accept two revisions in different"
2562
2366
                " branches." % command_name)
2563
 
        if start_spec.spec is None:
2564
 
            # Avoid loading all the history.
2565
 
            rev1 = RevisionInfo(branch, None, None)
2566
 
        else:
2567
 
            rev1 = start_spec.in_history(branch)
 
2367
        rev1 = start_spec.in_history(branch)
2568
2368
        # Avoid loading all of history when we know a missing
2569
2369
        # end of range means the last revision ...
2570
2370
        if end_spec.spec is None:
2599
2399
 
2600
2400
 
2601
2401
class cmd_touching_revisions(Command):
2602
 
    __doc__ = """Return revision-ids which affected a particular file.
 
2402
    """Return revision-ids which affected a particular file.
2603
2403
 
2604
2404
    A more user-friendly interface is "bzr log FILE".
2605
2405
    """
2610
2410
    @display_command
2611
2411
    def run(self, filename):
2612
2412
        tree, relpath = WorkingTree.open_containing(filename)
 
2413
        b = tree.branch
2613
2414
        file_id = tree.path2id(relpath)
2614
 
        b = tree.branch
2615
 
        self.add_cleanup(b.lock_read().unlock)
2616
 
        touching_revs = log.find_touching_revisions(b, file_id)
2617
 
        for revno, revision_id, what in touching_revs:
 
2415
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
2618
2416
            self.outf.write("%6d %s\n" % (revno, what))
2619
2417
 
2620
2418
 
2621
2419
class cmd_ls(Command):
2622
 
    __doc__ = """List files in a tree.
 
2420
    """List files in a tree.
2623
2421
    """
2624
2422
 
2625
2423
    _see_also = ['status', 'cat']
2631
2429
                   help='Recurse into subdirectories.'),
2632
2430
            Option('from-root',
2633
2431
                   help='Print paths relative to the root of the branch.'),
2634
 
            Option('unknown', short_name='u',
2635
 
                help='Print unknown files.'),
 
2432
            Option('unknown', help='Print unknown files.'),
2636
2433
            Option('versioned', help='Print versioned files.',
2637
2434
                   short_name='V'),
2638
 
            Option('ignored', short_name='i',
2639
 
                help='Print ignored files.'),
2640
 
            Option('kind', short_name='k',
 
2435
            Option('ignored', help='Print ignored files.'),
 
2436
            Option('null',
 
2437
                   help='Write an ascii NUL (\\0) separator '
 
2438
                   'between files rather than a newline.'),
 
2439
            Option('kind',
2641
2440
                   help='List entries of a particular kind: file, directory, symlink.',
2642
2441
                   type=unicode),
2643
 
            'null',
2644
2442
            'show-ids',
2645
 
            'directory',
2646
2443
            ]
2647
2444
    @display_command
2648
2445
    def run(self, revision=None, verbose=False,
2649
2446
            recursive=False, from_root=False,
2650
2447
            unknown=False, versioned=False, ignored=False,
2651
 
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2448
            null=False, kind=None, show_ids=False, path=None):
2652
2449
 
2653
2450
        if kind and kind not in ('file', 'directory', 'symlink'):
2654
2451
            raise errors.BzrCommandError('invalid kind specified')
2666
2463
                raise errors.BzrCommandError('cannot specify both --from-root'
2667
2464
                                             ' and PATH')
2668
2465
            fs_path = path
2669
 
        tree, branch, relpath = \
2670
 
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2466
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2467
            fs_path)
2671
2468
 
2672
2469
        # Calculate the prefix to use
2673
2470
        prefix = None
2674
2471
        if from_root:
2675
2472
            if relpath:
2676
2473
                prefix = relpath + '/'
2677
 
        elif fs_path != '.' and not fs_path.endswith('/'):
 
2474
        elif fs_path != '.':
2678
2475
            prefix = fs_path + '/'
2679
2476
 
2680
2477
        if revision is not None or tree is None:
2688
2485
                view_str = views.view_display_str(view_files)
2689
2486
                note("Ignoring files outside view. View is %s" % view_str)
2690
2487
 
2691
 
        self.add_cleanup(tree.lock_read().unlock)
2692
 
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2693
 
            from_dir=relpath, recursive=recursive):
2694
 
            # Apply additional masking
2695
 
            if not all and not selection[fc]:
2696
 
                continue
2697
 
            if kind is not None and fkind != kind:
2698
 
                continue
2699
 
            if apply_view:
2700
 
                try:
2701
 
                    if relpath:
2702
 
                        fullpath = osutils.pathjoin(relpath, fp)
2703
 
                    else:
2704
 
                        fullpath = fp
2705
 
                    views.check_path_in_view(tree, fullpath)
2706
 
                except errors.FileOutsideView:
2707
 
                    continue
 
2488
        tree.lock_read()
 
2489
        try:
 
2490
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
2491
                from_dir=relpath, recursive=recursive):
 
2492
                # Apply additional masking
 
2493
                if not all and not selection[fc]:
 
2494
                    continue
 
2495
                if kind is not None and fkind != kind:
 
2496
                    continue
 
2497
                if apply_view:
 
2498
                    try:
 
2499
                        if relpath:
 
2500
                            fullpath = osutils.pathjoin(relpath, fp)
 
2501
                        else:
 
2502
                            fullpath = fp
 
2503
                        views.check_path_in_view(tree, fullpath)
 
2504
                    except errors.FileOutsideView:
 
2505
                        continue
2708
2506
 
2709
 
            # Output the entry
2710
 
            if prefix:
2711
 
                fp = osutils.pathjoin(prefix, fp)
2712
 
            kindch = entry.kind_character()
2713
 
            outstring = fp + kindch
2714
 
            ui.ui_factory.clear_term()
2715
 
            if verbose:
2716
 
                outstring = '%-8s %s' % (fc, outstring)
2717
 
                if show_ids and fid is not None:
2718
 
                    outstring = "%-50s %s" % (outstring, fid)
2719
 
                self.outf.write(outstring + '\n')
2720
 
            elif null:
2721
 
                self.outf.write(fp + '\0')
2722
 
                if show_ids:
2723
 
                    if fid is not None:
2724
 
                        self.outf.write(fid)
2725
 
                    self.outf.write('\0')
2726
 
                self.outf.flush()
2727
 
            else:
2728
 
                if show_ids:
2729
 
                    if fid is not None:
2730
 
                        my_id = fid
2731
 
                    else:
2732
 
                        my_id = ''
2733
 
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
2734
 
                else:
 
2507
                # Output the entry
 
2508
                if prefix:
 
2509
                    fp = osutils.pathjoin(prefix, fp)
 
2510
                kindch = entry.kind_character()
 
2511
                outstring = fp + kindch
 
2512
                ui.ui_factory.clear_term()
 
2513
                if verbose:
 
2514
                    outstring = '%-8s %s' % (fc, outstring)
 
2515
                    if show_ids and fid is not None:
 
2516
                        outstring = "%-50s %s" % (outstring, fid)
2735
2517
                    self.outf.write(outstring + '\n')
 
2518
                elif null:
 
2519
                    self.outf.write(fp + '\0')
 
2520
                    if show_ids:
 
2521
                        if fid is not None:
 
2522
                            self.outf.write(fid)
 
2523
                        self.outf.write('\0')
 
2524
                    self.outf.flush()
 
2525
                else:
 
2526
                    if show_ids:
 
2527
                        if fid is not None:
 
2528
                            my_id = fid
 
2529
                        else:
 
2530
                            my_id = ''
 
2531
                        self.outf.write('%-50s %s\n' % (outstring, my_id))
 
2532
                    else:
 
2533
                        self.outf.write(outstring + '\n')
 
2534
        finally:
 
2535
            tree.unlock()
2736
2536
 
2737
2537
 
2738
2538
class cmd_unknowns(Command):
2739
 
    __doc__ = """List unknown files.
 
2539
    """List unknown files.
2740
2540
    """
2741
2541
 
2742
2542
    hidden = True
2743
2543
    _see_also = ['ls']
2744
 
    takes_options = ['directory']
2745
2544
 
2746
2545
    @display_command
2747
 
    def run(self, directory=u'.'):
2748
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
2546
    def run(self):
 
2547
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
2749
2548
            self.outf.write(osutils.quotefn(f) + '\n')
2750
2549
 
2751
2550
 
2752
2551
class cmd_ignore(Command):
2753
 
    __doc__ = """Ignore specified files or patterns.
 
2552
    """Ignore specified files or patterns.
2754
2553
 
2755
2554
    See ``bzr help patterns`` for details on the syntax of patterns.
2756
2555
 
2757
 
    If a .bzrignore file does not exist, the ignore command
2758
 
    will create one and add the specified files or patterns to the newly
2759
 
    created file. The ignore command will also automatically add the 
2760
 
    .bzrignore file to be versioned. Creating a .bzrignore file without
2761
 
    the use of the ignore command will require an explicit add command.
2762
 
 
2763
2556
    To remove patterns from the ignore list, edit the .bzrignore file.
2764
2557
    After adding, editing or deleting that file either indirectly by
2765
2558
    using this command or directly by using an editor, be sure to commit
2766
2559
    it.
2767
 
    
2768
 
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2769
 
    the global ignore file can be found in the application data directory as
2770
 
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2771
 
    Global ignores are not touched by this command. The global ignore file
2772
 
    can be edited directly using an editor.
2773
 
 
2774
 
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2775
 
    precedence over regular ignores.  Such exceptions are used to specify
2776
 
    files that should be versioned which would otherwise be ignored.
2777
 
    
2778
 
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2779
 
    precedence over the '!' exception patterns.
2780
 
 
2781
 
    :Notes: 
2782
 
        
2783
 
    * Ignore patterns containing shell wildcards must be quoted from
2784
 
      the shell on Unix.
2785
 
 
2786
 
    * Ignore patterns starting with "#" act as comments in the ignore file.
2787
 
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
2560
 
 
2561
    Note: ignore patterns containing shell wildcards must be quoted from
 
2562
    the shell on Unix.
2788
2563
 
2789
2564
    :Examples:
2790
2565
        Ignore the top level Makefile::
2791
2566
 
2792
2567
            bzr ignore ./Makefile
2793
2568
 
2794
 
        Ignore .class files in all directories...::
 
2569
        Ignore class files in all directories::
2795
2570
 
2796
2571
            bzr ignore "*.class"
2797
2572
 
2798
 
        ...but do not ignore "special.class"::
2799
 
 
2800
 
            bzr ignore "!special.class"
2801
 
 
2802
 
        Ignore files whose name begins with the "#" character::
2803
 
 
2804
 
            bzr ignore "RE:^#"
2805
 
 
2806
2573
        Ignore .o files under the lib directory::
2807
2574
 
2808
2575
            bzr ignore "lib/**/*.o"
2814
2581
        Ignore everything but the "debian" toplevel directory::
2815
2582
 
2816
2583
            bzr ignore "RE:(?!debian/).*"
2817
 
        
2818
 
        Ignore everything except the "local" toplevel directory,
2819
 
        but always ignore autosave files ending in ~, even under local/::
2820
 
        
2821
 
            bzr ignore "*"
2822
 
            bzr ignore "!./local"
2823
 
            bzr ignore "!!*~"
2824
2584
    """
2825
2585
 
2826
2586
    _see_also = ['status', 'ignored', 'patterns']
2827
2587
    takes_args = ['name_pattern*']
2828
 
    takes_options = ['directory',
2829
 
        Option('default-rules',
2830
 
               help='Display the default ignore rules that bzr uses.')
 
2588
    takes_options = [
 
2589
        Option('old-default-rules',
 
2590
               help='Write out the ignore rules bzr < 0.9 always used.')
2831
2591
        ]
2832
2592
 
2833
 
    def run(self, name_pattern_list=None, default_rules=None,
2834
 
            directory=u'.'):
 
2593
    def run(self, name_pattern_list=None, old_default_rules=None):
2835
2594
        from bzrlib import ignores
2836
 
        if default_rules is not None:
2837
 
            # dump the default rules and exit
2838
 
            for pattern in ignores.USER_DEFAULTS:
2839
 
                self.outf.write("%s\n" % pattern)
 
2595
        if old_default_rules is not None:
 
2596
            # dump the rules and exit
 
2597
            for pattern in ignores.OLD_DEFAULTS:
 
2598
                print pattern
2840
2599
            return
2841
2600
        if not name_pattern_list:
2842
2601
            raise errors.BzrCommandError("ignore requires at least one "
2843
 
                "NAME_PATTERN or --default-rules.")
 
2602
                                  "NAME_PATTERN or --old-default-rules")
2844
2603
        name_pattern_list = [globbing.normalize_pattern(p)
2845
2604
                             for p in name_pattern_list]
2846
 
        bad_patterns = ''
2847
 
        for p in name_pattern_list:
2848
 
            if not globbing.Globster.is_pattern_valid(p):
2849
 
                bad_patterns += ('\n  %s' % p)
2850
 
        if bad_patterns:
2851
 
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2852
 
            ui.ui_factory.show_error(msg)
2853
 
            raise errors.InvalidPattern('')
2854
2605
        for name_pattern in name_pattern_list:
2855
2606
            if (name_pattern[0] == '/' or
2856
2607
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2857
2608
                raise errors.BzrCommandError(
2858
2609
                    "NAME_PATTERN should not be an absolute path")
2859
 
        tree, relpath = WorkingTree.open_containing(directory)
 
2610
        tree, relpath = WorkingTree.open_containing(u'.')
2860
2611
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2861
2612
        ignored = globbing.Globster(name_pattern_list)
2862
2613
        matches = []
2863
 
        self.add_cleanup(tree.lock_read().unlock)
 
2614
        tree.lock_read()
2864
2615
        for entry in tree.list_files():
2865
2616
            id = entry[3]
2866
2617
            if id is not None:
2867
2618
                filename = entry[0]
2868
2619
                if ignored.match(filename):
2869
 
                    matches.append(filename)
 
2620
                    matches.append(filename.encode('utf-8'))
 
2621
        tree.unlock()
2870
2622
        if len(matches) > 0:
2871
 
            self.outf.write("Warning: the following files are version controlled and"
2872
 
                  " match your ignore pattern:\n%s"
2873
 
                  "\nThese files will continue to be version controlled"
2874
 
                  " unless you 'bzr remove' them.\n" % ("\n".join(matches),))
 
2623
            print "Warning: the following files are version controlled and" \
 
2624
                  " match your ignore pattern:\n%s" \
 
2625
                  "\nThese files will continue to be version controlled" \
 
2626
                  " unless you 'bzr remove' them." % ("\n".join(matches),)
2875
2627
 
2876
2628
 
2877
2629
class cmd_ignored(Command):
2878
 
    __doc__ = """List ignored files and the patterns that matched them.
 
2630
    """List ignored files and the patterns that matched them.
2879
2631
 
2880
2632
    List all the ignored files and the ignore pattern that caused the file to
2881
2633
    be ignored.
2887
2639
 
2888
2640
    encoding_type = 'replace'
2889
2641
    _see_also = ['ignore', 'ls']
2890
 
    takes_options = ['directory']
2891
2642
 
2892
2643
    @display_command
2893
 
    def run(self, directory=u'.'):
2894
 
        tree = WorkingTree.open_containing(directory)[0]
2895
 
        self.add_cleanup(tree.lock_read().unlock)
2896
 
        for path, file_class, kind, file_id, entry in tree.list_files():
2897
 
            if file_class != 'I':
2898
 
                continue
2899
 
            ## XXX: Slightly inefficient since this was already calculated
2900
 
            pat = tree.is_ignored(path)
2901
 
            self.outf.write('%-50s %s\n' % (path, pat))
 
2644
    def run(self):
 
2645
        tree = WorkingTree.open_containing(u'.')[0]
 
2646
        tree.lock_read()
 
2647
        try:
 
2648
            for path, file_class, kind, file_id, entry in tree.list_files():
 
2649
                if file_class != 'I':
 
2650
                    continue
 
2651
                ## XXX: Slightly inefficient since this was already calculated
 
2652
                pat = tree.is_ignored(path)
 
2653
                self.outf.write('%-50s %s\n' % (path, pat))
 
2654
        finally:
 
2655
            tree.unlock()
2902
2656
 
2903
2657
 
2904
2658
class cmd_lookup_revision(Command):
2905
 
    __doc__ = """Lookup the revision-id from a revision-number
 
2659
    """Lookup the revision-id from a revision-number
2906
2660
 
2907
2661
    :Examples:
2908
2662
        bzr lookup-revision 33
2909
2663
    """
2910
2664
    hidden = True
2911
2665
    takes_args = ['revno']
2912
 
    takes_options = ['directory']
2913
2666
 
2914
2667
    @display_command
2915
 
    def run(self, revno, directory=u'.'):
 
2668
    def run(self, revno):
2916
2669
        try:
2917
2670
            revno = int(revno)
2918
2671
        except ValueError:
2919
 
            raise errors.BzrCommandError("not a valid revision-number: %r"
2920
 
                                         % revno)
2921
 
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2922
 
        self.outf.write("%s\n" % revid)
 
2672
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
 
2673
 
 
2674
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2923
2675
 
2924
2676
 
2925
2677
class cmd_export(Command):
2926
 
    __doc__ = """Export current or past revision to a destination directory or archive.
 
2678
    """Export current or past revision to a destination directory or archive.
2927
2679
 
2928
2680
    If no revision is specified this exports the last committed revision.
2929
2681
 
2950
2702
         zip                          .zip
2951
2703
      =================       =========================
2952
2704
    """
2953
 
    encoding = 'exact'
2954
2705
    takes_args = ['dest', 'branch_or_subdir?']
2955
 
    takes_options = ['directory',
 
2706
    takes_options = [
2956
2707
        Option('format',
2957
2708
               help="Type of file to export to.",
2958
2709
               type=unicode),
2962
2713
        Option('root',
2963
2714
               type=str,
2964
2715
               help="Name of the root directory inside the exported file."),
2965
 
        Option('per-file-timestamps',
2966
 
               help='Set modification time of files to that of the last '
2967
 
                    'revision in which it was changed.'),
2968
2716
        ]
2969
2717
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2970
 
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
 
2718
        root=None, filters=False):
2971
2719
        from bzrlib.export import export
2972
2720
 
2973
2721
        if branch_or_subdir is None:
2974
 
            tree = WorkingTree.open_containing(directory)[0]
 
2722
            tree = WorkingTree.open_containing(u'.')[0]
2975
2723
            b = tree.branch
2976
2724
            subdir = None
2977
2725
        else:
2980
2728
 
2981
2729
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2982
2730
        try:
2983
 
            export(rev_tree, dest, format, root, subdir, filtered=filters,
2984
 
                   per_file_timestamps=per_file_timestamps)
 
2731
            export(rev_tree, dest, format, root, subdir, filtered=filters)
2985
2732
        except errors.NoSuchExportFormat, e:
2986
2733
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2987
2734
 
2988
2735
 
2989
2736
class cmd_cat(Command):
2990
 
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
2737
    """Write the contents of a file as of a given revision to standard output.
2991
2738
 
2992
2739
    If no revision is nominated, the last revision is used.
2993
2740
 
2996
2743
    """
2997
2744
 
2998
2745
    _see_also = ['ls']
2999
 
    takes_options = ['directory',
 
2746
    takes_options = [
3000
2747
        Option('name-from-revision', help='The path name in the old tree.'),
3001
2748
        Option('filters', help='Apply content filters to display the '
3002
2749
                'convenience form.'),
3007
2754
 
3008
2755
    @display_command
3009
2756
    def run(self, filename, revision=None, name_from_revision=False,
3010
 
            filters=False, directory=None):
 
2757
            filters=False):
3011
2758
        if revision is not None and len(revision) != 1:
3012
2759
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
3013
2760
                                         " one revision specifier")
3014
2761
        tree, branch, relpath = \
3015
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
3016
 
        self.add_cleanup(branch.lock_read().unlock)
3017
 
        return self._run(tree, branch, relpath, filename, revision,
3018
 
                         name_from_revision, filters)
 
2762
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2763
        branch.lock_read()
 
2764
        try:
 
2765
            return self._run(tree, branch, relpath, filename, revision,
 
2766
                             name_from_revision, filters)
 
2767
        finally:
 
2768
            branch.unlock()
3019
2769
 
3020
2770
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
3021
2771
        filtered):
3022
2772
        if tree is None:
3023
2773
            tree = b.basis_tree()
3024
2774
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3025
 
        self.add_cleanup(rev_tree.lock_read().unlock)
3026
2775
 
3027
2776
        old_file_id = rev_tree.path2id(relpath)
3028
2777
 
3063
2812
            chunks = content.splitlines(True)
3064
2813
            content = filtered_output_bytes(chunks, filters,
3065
2814
                ContentFilterContext(relpath, rev_tree))
3066
 
            self.cleanup_now()
3067
2815
            self.outf.writelines(content)
3068
2816
        else:
3069
 
            self.cleanup_now()
3070
2817
            self.outf.write(content)
3071
2818
 
3072
2819
 
3073
2820
class cmd_local_time_offset(Command):
3074
 
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
2821
    """Show the offset in seconds from GMT to local time."""
3075
2822
    hidden = True
3076
2823
    @display_command
3077
2824
    def run(self):
3078
 
        self.outf.write("%s\n" % osutils.local_time_offset())
 
2825
        print osutils.local_time_offset()
3079
2826
 
3080
2827
 
3081
2828
 
3082
2829
class cmd_commit(Command):
3083
 
    __doc__ = """Commit changes into a new revision.
 
2830
    """Commit changes into a new revision.
3084
2831
 
3085
2832
    An explanatory message needs to be given for each commit. This is
3086
2833
    often done by using the --message option (getting the message from the
3134
2881
      to trigger updates to external systems like bug trackers. The --fixes
3135
2882
      option can be used to record the association between a revision and
3136
2883
      one or more bugs. See ``bzr help bugs`` for details.
 
2884
 
 
2885
      A selective commit may fail in some cases where the committed
 
2886
      tree would be invalid. Consider::
 
2887
  
 
2888
        bzr init foo
 
2889
        mkdir foo/bar
 
2890
        bzr add foo/bar
 
2891
        bzr commit foo -m "committing foo"
 
2892
        bzr mv foo/bar foo/baz
 
2893
        mkdir foo/bar
 
2894
        bzr add foo/bar
 
2895
        bzr commit foo/bar -m "committing bar but not baz"
 
2896
  
 
2897
      In the example above, the last commit will fail by design. This gives
 
2898
      the user the opportunity to decide whether they want to commit the
 
2899
      rename at the same time, separately first, or not at all. (As a general
 
2900
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
3137
2901
    """
 
2902
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
2903
 
 
2904
    # TODO: Strict commit that fails if there are deleted files.
 
2905
    #       (what does "deleted files" mean ??)
 
2906
 
 
2907
    # TODO: Give better message for -s, --summary, used by tla people
 
2908
 
 
2909
    # XXX: verbose currently does nothing
3138
2910
 
3139
2911
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
3140
2912
    takes_args = ['selected*']
3154
2926
             Option('strict',
3155
2927
                    help="Refuse to commit if there are unknown "
3156
2928
                    "files in the working tree."),
3157
 
             Option('commit-time', type=str,
3158
 
                    help="Manually set a commit time using commit date "
3159
 
                    "format, e.g. '2009-10-10 08:00:00 +0100'."),
3160
2929
             ListOption('fixes', type=str,
3161
2930
                    help="Mark a bug as being fixed by this revision "
3162
2931
                         "(see \"bzr help bugs\")."),
3169
2938
                         "the master branch until a normal commit "
3170
2939
                         "is performed."
3171
2940
                    ),
3172
 
             Option('show-diff', short_name='p',
3173
 
                    help='When no message is supplied, show the diff along'
3174
 
                    ' with the status summary in the message editor.'),
3175
 
             Option('lossy', 
3176
 
                    help='When committing to a foreign version control '
3177
 
                    'system do not push data that can not be natively '
3178
 
                    'represented.'),
 
2941
              Option('show-diff',
 
2942
                     help='When no message is supplied, show the diff along'
 
2943
                     ' with the status summary in the message editor.'),
3179
2944
             ]
3180
2945
    aliases = ['ci', 'checkin']
3181
2946
 
3200
2965
 
3201
2966
    def run(self, message=None, file=None, verbose=False, selected_list=None,
3202
2967
            unchanged=False, strict=False, local=False, fixes=None,
3203
 
            author=None, show_diff=False, exclude=None, commit_time=None,
3204
 
            lossy=False):
 
2968
            author=None, show_diff=False, exclude=None):
3205
2969
        from bzrlib.errors import (
3206
2970
            PointlessCommit,
3207
2971
            ConflictsInTree,
3210
2974
        from bzrlib.msgeditor import (
3211
2975
            edit_commit_message_encoded,
3212
2976
            generate_commit_message_template,
3213
 
            make_commit_message_template_encoded,
3214
 
            set_commit_message,
 
2977
            make_commit_message_template_encoded
3215
2978
        )
3216
2979
 
3217
 
        commit_stamp = offset = None
3218
 
        if commit_time is not None:
3219
 
            try:
3220
 
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3221
 
            except ValueError, e:
3222
 
                raise errors.BzrCommandError(
3223
 
                    "Could not parse --commit-time: " + str(e))
 
2980
        # TODO: Need a blackbox test for invoking the external editor; may be
 
2981
        # slightly problematic to run this cross-platform.
 
2982
 
 
2983
        # TODO: do more checks that the commit will succeed before
 
2984
        # spending the user's valuable time typing a commit message.
3224
2985
 
3225
2986
        properties = {}
3226
2987
 
3227
 
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
2988
        tree, selected_list = tree_files(selected_list)
3228
2989
        if selected_list == ['']:
3229
2990
            # workaround - commit of root of tree should be exactly the same
3230
2991
            # as just default commit in that tree, and succeed even though
3241
3002
        if local and not tree.branch.get_bound_location():
3242
3003
            raise errors.LocalRequiresBoundBranch()
3243
3004
 
3244
 
        if message is not None:
3245
 
            try:
3246
 
                file_exists = osutils.lexists(message)
3247
 
            except UnicodeError:
3248
 
                # The commit message contains unicode characters that can't be
3249
 
                # represented in the filesystem encoding, so that can't be a
3250
 
                # file.
3251
 
                file_exists = False
3252
 
            if file_exists:
3253
 
                warning_msg = (
3254
 
                    'The commit message is a file name: "%(f)s".\n'
3255
 
                    '(use --file "%(f)s" to take commit message from that file)'
3256
 
                    % { 'f': message })
3257
 
                ui.ui_factory.show_warning(warning_msg)
3258
 
            if '\r' in message:
3259
 
                message = message.replace('\r\n', '\n')
3260
 
                message = message.replace('\r', '\n')
3261
 
            if file:
3262
 
                raise errors.BzrCommandError(
3263
 
                    "please specify either --message or --file")
3264
 
 
3265
3005
        def get_message(commit_obj):
3266
3006
            """Callback to get commit message"""
3267
 
            if file:
3268
 
                f = open(file)
3269
 
                try:
3270
 
                    my_message = f.read().decode(osutils.get_user_encoding())
3271
 
                finally:
3272
 
                    f.close()
3273
 
            elif message is not None:
3274
 
                my_message = message
3275
 
            else:
3276
 
                # No message supplied: make one up.
3277
 
                # text is the status of the tree
3278
 
                text = make_commit_message_template_encoded(tree,
 
3007
            my_message = message
 
3008
            if my_message is None and not file:
 
3009
                t = make_commit_message_template_encoded(tree,
3279
3010
                        selected_list, diff=show_diff,
3280
3011
                        output_encoding=osutils.get_user_encoding())
3281
 
                # start_message is the template generated from hooks
3282
 
                # XXX: Warning - looks like hooks return unicode,
3283
 
                # make_commit_message_template_encoded returns user encoding.
3284
 
                # We probably want to be using edit_commit_message instead to
3285
 
                # avoid this.
3286
 
                my_message = set_commit_message(commit_obj)
3287
 
                if my_message is None:
3288
 
                    start_message = generate_commit_message_template(commit_obj)
3289
 
                    my_message = edit_commit_message_encoded(text,
3290
 
                        start_message=start_message)
 
3012
                start_message = generate_commit_message_template(commit_obj)
 
3013
                my_message = edit_commit_message_encoded(t,
 
3014
                    start_message=start_message)
3291
3015
                if my_message is None:
3292
3016
                    raise errors.BzrCommandError("please specify a commit"
3293
3017
                        " message with either --message or --file")
 
3018
            elif my_message and file:
 
3019
                raise errors.BzrCommandError(
 
3020
                    "please specify either --message or --file")
 
3021
            if file:
 
3022
                my_message = codecs.open(file, 'rt',
 
3023
                                         osutils.get_user_encoding()).read()
3294
3024
            if my_message == "":
3295
3025
                raise errors.BzrCommandError("empty commit message specified")
3296
3026
            return my_message
3297
3027
 
3298
 
        # The API permits a commit with a filter of [] to mean 'select nothing'
3299
 
        # but the command line should not do that.
3300
 
        if not selected_list:
3301
 
            selected_list = None
3302
3028
        try:
3303
3029
            tree.commit(message_callback=get_message,
3304
3030
                        specific_files=selected_list,
3305
3031
                        allow_pointless=unchanged, strict=strict, local=local,
3306
3032
                        reporter=None, verbose=verbose, revprops=properties,
3307
 
                        authors=author, timestamp=commit_stamp,
3308
 
                        timezone=offset,
3309
 
                        exclude=tree.safe_relpath_files(exclude),
3310
 
                        lossy=lossy)
 
3033
                        authors=author,
 
3034
                        exclude=safe_relpath_files(tree, exclude))
3311
3035
        except PointlessCommit:
 
3036
            # FIXME: This should really happen before the file is read in;
 
3037
            # perhaps prepare the commit; get the message; then actually commit
3312
3038
            raise errors.BzrCommandError("No changes to commit."
3313
 
                " Please 'bzr add' the files you want to commit, or use"
3314
 
                " --unchanged to force an empty commit.")
 
3039
                              " Use --unchanged to commit anyhow.")
3315
3040
        except ConflictsInTree:
3316
3041
            raise errors.BzrCommandError('Conflicts detected in working '
3317
3042
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3320
3045
            raise errors.BzrCommandError("Commit refused because there are"
3321
3046
                              " unknown files in the working tree.")
3322
3047
        except errors.BoundBranchOutOfDate, e:
3323
 
            e.extra_help = ("\n"
3324
 
                'To commit to master branch, run update and then commit.\n'
3325
 
                'You can also pass --local to commit to continue working '
3326
 
                'disconnected.')
3327
 
            raise
 
3048
            raise errors.BzrCommandError(str(e) + "\n"
 
3049
            'To commit to master branch, run update and then commit.\n'
 
3050
            'You can also pass --local to commit to continue working '
 
3051
            'disconnected.')
3328
3052
 
3329
3053
 
3330
3054
class cmd_check(Command):
3331
 
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3055
    """Validate working tree structure, branch consistency and repository history.
3332
3056
 
3333
3057
    This command checks various invariants about branch and repository storage
3334
3058
    to detect data corruption or bzr bugs.
3398
3122
 
3399
3123
 
3400
3124
class cmd_upgrade(Command):
3401
 
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
3402
 
 
3403
 
    When the default format has changed after a major new release of
3404
 
    Bazaar, you may be informed during certain operations that you
3405
 
    should upgrade. Upgrading to a newer format may improve performance
3406
 
    or make new features available. It may however limit interoperability
3407
 
    with older repositories or with older versions of Bazaar.
3408
 
 
3409
 
    If you wish to upgrade to a particular format rather than the
3410
 
    current default, that can be specified using the --format option.
3411
 
    As a consequence, you can use the upgrade command this way to
3412
 
    "downgrade" to an earlier format, though some conversions are
3413
 
    a one way process (e.g. changing from the 1.x default to the
3414
 
    2.x default) so downgrading is not always possible.
3415
 
 
3416
 
    A backup.bzr.~#~ directory is created at the start of the conversion
3417
 
    process (where # is a number). By default, this is left there on
3418
 
    completion. If the conversion fails, delete the new .bzr directory
3419
 
    and rename this one back in its place. Use the --clean option to ask
3420
 
    for the backup.bzr directory to be removed on successful conversion.
3421
 
    Alternatively, you can delete it by hand if everything looks good
3422
 
    afterwards.
3423
 
 
3424
 
    If the location given is a shared repository, dependent branches
3425
 
    are also converted provided the repository converts successfully.
3426
 
    If the conversion of a branch fails, remaining branches are still
3427
 
    tried.
3428
 
 
3429
 
    For more information on upgrades, see the Bazaar Upgrade Guide,
3430
 
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
 
3125
    """Upgrade branch storage to current format.
 
3126
 
 
3127
    The check command or bzr developers may sometimes advise you to run
 
3128
    this command. When the default format has changed you may also be warned
 
3129
    during other operations to upgrade.
3431
3130
    """
3432
3131
 
3433
 
    _see_also = ['check', 'reconcile', 'formats']
 
3132
    _see_also = ['check']
3434
3133
    takes_args = ['url?']
3435
3134
    takes_options = [
3436
 
        RegistryOption('format',
3437
 
            help='Upgrade to a specific format.  See "bzr help'
3438
 
                 ' formats" for details.',
3439
 
            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3440
 
            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3441
 
            value_switches=True, title='Branch format'),
3442
 
        Option('clean',
3443
 
            help='Remove the backup.bzr directory if successful.'),
3444
 
        Option('dry-run',
3445
 
            help="Show what would be done, but don't actually do anything."),
3446
 
    ]
 
3135
                    RegistryOption('format',
 
3136
                        help='Upgrade to a specific format.  See "bzr help'
 
3137
                             ' formats" for details.',
 
3138
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3139
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
 
3140
                        value_switches=True, title='Branch format'),
 
3141
                    ]
3447
3142
 
3448
 
    def run(self, url='.', format=None, clean=False, dry_run=False):
 
3143
    def run(self, url='.', format=None):
3449
3144
        from bzrlib.upgrade import upgrade
3450
 
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3451
 
        if exceptions:
3452
 
            if len(exceptions) == 1:
3453
 
                # Compatibility with historical behavior
3454
 
                raise exceptions[0]
3455
 
            else:
3456
 
                return 3
 
3145
        upgrade(url, format)
3457
3146
 
3458
3147
 
3459
3148
class cmd_whoami(Command):
3460
 
    __doc__ = """Show or set bzr user id.
 
3149
    """Show or set bzr user id.
3461
3150
 
3462
3151
    :Examples:
3463
3152
        Show the email of the current user::
3468
3157
 
3469
3158
            bzr whoami "Frank Chu <fchu@example.com>"
3470
3159
    """
3471
 
    takes_options = [ 'directory',
3472
 
                      Option('email',
 
3160
    takes_options = [ Option('email',
3473
3161
                             help='Display email address only.'),
3474
3162
                      Option('branch',
3475
3163
                             help='Set identity for the current branch instead of '
3479
3167
    encoding_type = 'replace'
3480
3168
 
3481
3169
    @display_command
3482
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
3170
    def run(self, email=False, branch=False, name=None):
3483
3171
        if name is None:
3484
 
            if directory is None:
3485
 
                # use branch if we're inside one; otherwise global config
3486
 
                try:
3487
 
                    c = Branch.open_containing(u'.')[0].get_config()
3488
 
                except errors.NotBranchError:
3489
 
                    c = _mod_config.GlobalConfig()
3490
 
            else:
3491
 
                c = Branch.open(directory).get_config()
 
3172
            # use branch if we're inside one; otherwise global config
 
3173
            try:
 
3174
                c = Branch.open_containing('.')[0].get_config()
 
3175
            except errors.NotBranchError:
 
3176
                c = config.GlobalConfig()
3492
3177
            if email:
3493
3178
                self.outf.write(c.user_email() + '\n')
3494
3179
            else:
3495
3180
                self.outf.write(c.username() + '\n')
3496
3181
            return
3497
3182
 
3498
 
        if email:
3499
 
            raise errors.BzrCommandError("--email can only be used to display existing "
3500
 
                                         "identity")
3501
 
 
3502
3183
        # display a warning if an email address isn't included in the given name.
3503
3184
        try:
3504
 
            _mod_config.extract_email_address(name)
 
3185
            config.extract_email_address(name)
3505
3186
        except errors.NoEmailInUsername, e:
3506
3187
            warning('"%s" does not seem to contain an email address.  '
3507
3188
                    'This is allowed, but not recommended.', name)
3508
3189
 
3509
3190
        # use global config unless --branch given
3510
3191
        if branch:
3511
 
            if directory is None:
3512
 
                c = Branch.open_containing(u'.')[0].get_config()
3513
 
            else:
3514
 
                c = Branch.open(directory).get_config()
 
3192
            c = Branch.open_containing('.')[0].get_config()
3515
3193
        else:
3516
 
            c = _mod_config.GlobalConfig()
 
3194
            c = config.GlobalConfig()
3517
3195
        c.set_user_option('email', name)
3518
3196
 
3519
3197
 
3520
3198
class cmd_nick(Command):
3521
 
    __doc__ = """Print or set the branch nickname.
 
3199
    """Print or set the branch nickname.
3522
3200
 
3523
3201
    If unset, the tree root directory name is used as the nickname.
3524
3202
    To print the current nickname, execute with no argument.
3529
3207
 
3530
3208
    _see_also = ['info']
3531
3209
    takes_args = ['nickname?']
3532
 
    takes_options = ['directory']
3533
 
    def run(self, nickname=None, directory=u'.'):
3534
 
        branch = Branch.open_containing(directory)[0]
 
3210
    def run(self, nickname=None):
 
3211
        branch = Branch.open_containing(u'.')[0]
3535
3212
        if nickname is None:
3536
3213
            self.printme(branch)
3537
3214
        else:
3539
3216
 
3540
3217
    @display_command
3541
3218
    def printme(self, branch):
3542
 
        self.outf.write('%s\n' % branch.nick)
 
3219
        print branch.nick
3543
3220
 
3544
3221
 
3545
3222
class cmd_alias(Command):
3546
 
    __doc__ = """Set/unset and display aliases.
 
3223
    """Set/unset and display aliases.
3547
3224
 
3548
3225
    :Examples:
3549
3226
        Show the current aliases::
3586
3263
                'bzr alias --remove expects an alias to remove.')
3587
3264
        # If alias is not found, print something like:
3588
3265
        # unalias: foo: not found
3589
 
        c = _mod_config.GlobalConfig()
 
3266
        c = config.GlobalConfig()
3590
3267
        c.unset_alias(alias_name)
3591
3268
 
3592
3269
    @display_command
3593
3270
    def print_aliases(self):
3594
3271
        """Print out the defined aliases in a similar format to bash."""
3595
 
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3272
        aliases = config.GlobalConfig().get_aliases()
3596
3273
        for key, value in sorted(aliases.iteritems()):
3597
3274
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3598
3275
 
3608
3285
 
3609
3286
    def set_alias(self, alias_name, alias_command):
3610
3287
        """Save the alias in the global config."""
3611
 
        c = _mod_config.GlobalConfig()
 
3288
        c = config.GlobalConfig()
3612
3289
        c.set_alias(alias_name, alias_command)
3613
3290
 
3614
3291
 
3615
3292
class cmd_selftest(Command):
3616
 
    __doc__ = """Run internal test suite.
 
3293
    """Run internal test suite.
3617
3294
 
3618
3295
    If arguments are given, they are regular expressions that say which tests
3619
3296
    should run.  Tests matching any expression are run, and other tests are
3646
3323
    Tests that need working space on disk use a common temporary directory,
3647
3324
    typically inside $TMPDIR or /tmp.
3648
3325
 
3649
 
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3650
 
    into a pdb postmortem session.
3651
 
 
3652
 
    The --coverage=DIRNAME global option produces a report with covered code
3653
 
    indicated.
3654
 
 
3655
3326
    :Examples:
3656
3327
        Run only tests relating to 'ignore'::
3657
3328
 
3666
3337
    def get_transport_type(typestring):
3667
3338
        """Parse and return a transport specifier."""
3668
3339
        if typestring == "sftp":
3669
 
            from bzrlib.tests import stub_sftp
3670
 
            return stub_sftp.SFTPAbsoluteServer
3671
 
        elif typestring == "memory":
3672
 
            from bzrlib.tests import test_server
3673
 
            return memory.MemoryServer
3674
 
        elif typestring == "fakenfs":
3675
 
            from bzrlib.tests import test_server
3676
 
            return test_server.FakeNFSServer
 
3340
            from bzrlib.transport.sftp import SFTPAbsoluteServer
 
3341
            return SFTPAbsoluteServer
 
3342
        if typestring == "memory":
 
3343
            from bzrlib.transport.memory import MemoryServer
 
3344
            return MemoryServer
 
3345
        if typestring == "fakenfs":
 
3346
            from bzrlib.transport.fakenfs import FakeNFSServer
 
3347
            return FakeNFSServer
3677
3348
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3678
3349
            (typestring)
3679
3350
        raise errors.BzrCommandError(msg)
3690
3361
                                 'throughout the test suite.',
3691
3362
                            type=get_transport_type),
3692
3363
                     Option('benchmark',
3693
 
                            help='Run the benchmarks rather than selftests.',
3694
 
                            hidden=True),
 
3364
                            help='Run the benchmarks rather than selftests.'),
3695
3365
                     Option('lsprof-timed',
3696
3366
                            help='Generate lsprof output for benchmarked'
3697
3367
                                 ' sections of code.'),
3698
 
                     Option('lsprof-tests',
3699
 
                            help='Generate lsprof output for each test.'),
 
3368
                     Option('cache-dir', type=str,
 
3369
                            help='Cache intermediate benchmark output in this '
 
3370
                                 'directory.'),
3700
3371
                     Option('first',
3701
3372
                            help='Run all tests, but run specified tests first.',
3702
3373
                            short_name='f',
3711
3382
                     Option('randomize', type=str, argname="SEED",
3712
3383
                            help='Randomize the order of tests using the given'
3713
3384
                                 ' seed or "now" for the current time.'),
3714
 
                     ListOption('exclude', type=str, argname="PATTERN",
3715
 
                                short_name='x',
3716
 
                                help='Exclude tests that match this regular'
3717
 
                                ' expression.'),
 
3385
                     Option('exclude', type=str, argname="PATTERN",
 
3386
                            short_name='x',
 
3387
                            help='Exclude tests that match this regular'
 
3388
                                 ' expression.'),
3718
3389
                     Option('subunit',
3719
3390
                        help='Output test progress via subunit.'),
3720
3391
                     Option('strict', help='Fail on missing dependencies or '
3736
3407
 
3737
3408
    def run(self, testspecs_list=None, verbose=False, one=False,
3738
3409
            transport=None, benchmark=None,
3739
 
            lsprof_timed=None,
 
3410
            lsprof_timed=None, cache_dir=None,
3740
3411
            first=False, list_only=False,
3741
3412
            randomize=None, exclude=None, strict=False,
3742
3413
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3743
 
            parallel=None, lsprof_tests=False):
3744
 
        from bzrlib import tests
3745
 
 
 
3414
            parallel=None):
 
3415
        from bzrlib.tests import selftest
 
3416
        import bzrlib.benchmarks as benchmarks
 
3417
        from bzrlib.benchmarks import tree_creator
 
3418
 
 
3419
        # Make deprecation warnings visible, unless -Werror is set
 
3420
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3421
 
 
3422
        if cache_dir is not None:
 
3423
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3746
3424
        if testspecs_list is not None:
3747
3425
            pattern = '|'.join(testspecs_list)
3748
3426
        else:
3754
3432
                raise errors.BzrCommandError("subunit not available. subunit "
3755
3433
                    "needs to be installed to use --subunit.")
3756
3434
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3757
 
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3758
 
            # stdout, which would corrupt the subunit stream. 
3759
 
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3760
 
            # following code can be deleted when it's sufficiently deployed
3761
 
            # -- vila/mgz 20100514
3762
 
            if (sys.platform == "win32"
3763
 
                and getattr(sys.stdout, 'fileno', None) is not None):
3764
 
                import msvcrt
3765
 
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3766
3435
        if parallel:
3767
3436
            self.additional_selftest_args.setdefault(
3768
3437
                'suite_decorators', []).append(parallel)
3769
3438
        if benchmark:
3770
 
            raise errors.BzrCommandError(
3771
 
                "--benchmark is no longer supported from bzr 2.2; "
3772
 
                "use bzr-usertest instead")
3773
 
        test_suite_factory = None
3774
 
        if not exclude:
3775
 
            exclude_pattern = None
 
3439
            test_suite_factory = benchmarks.test_suite
 
3440
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3441
            verbose = not is_quiet()
 
3442
            # TODO: should possibly lock the history file...
 
3443
            benchfile = open(".perf_history", "at", buffering=1)
3776
3444
        else:
3777
 
            exclude_pattern = '(' + '|'.join(exclude) + ')'
3778
 
        selftest_kwargs = {"verbose": verbose,
3779
 
                          "pattern": pattern,
3780
 
                          "stop_on_failure": one,
3781
 
                          "transport": transport,
3782
 
                          "test_suite_factory": test_suite_factory,
3783
 
                          "lsprof_timed": lsprof_timed,
3784
 
                          "lsprof_tests": lsprof_tests,
3785
 
                          "matching_tests_first": first,
3786
 
                          "list_only": list_only,
3787
 
                          "random_seed": randomize,
3788
 
                          "exclude_pattern": exclude_pattern,
3789
 
                          "strict": strict,
3790
 
                          "load_list": load_list,
3791
 
                          "debug_flags": debugflag,
3792
 
                          "starting_with": starting_with
3793
 
                          }
3794
 
        selftest_kwargs.update(self.additional_selftest_args)
3795
 
 
3796
 
        # Make deprecation warnings visible, unless -Werror is set
3797
 
        cleanup = symbol_versioning.activate_deprecation_warnings(
3798
 
            override=False)
 
3445
            test_suite_factory = None
 
3446
            benchfile = None
3799
3447
        try:
3800
 
            result = tests.selftest(**selftest_kwargs)
 
3448
            selftest_kwargs = {"verbose": verbose,
 
3449
                              "pattern": pattern,
 
3450
                              "stop_on_failure": one,
 
3451
                              "transport": transport,
 
3452
                              "test_suite_factory": test_suite_factory,
 
3453
                              "lsprof_timed": lsprof_timed,
 
3454
                              "bench_history": benchfile,
 
3455
                              "matching_tests_first": first,
 
3456
                              "list_only": list_only,
 
3457
                              "random_seed": randomize,
 
3458
                              "exclude_pattern": exclude,
 
3459
                              "strict": strict,
 
3460
                              "load_list": load_list,
 
3461
                              "debug_flags": debugflag,
 
3462
                              "starting_with": starting_with
 
3463
                              }
 
3464
            selftest_kwargs.update(self.additional_selftest_args)
 
3465
            result = selftest(**selftest_kwargs)
3801
3466
        finally:
3802
 
            cleanup()
 
3467
            if benchfile is not None:
 
3468
                benchfile.close()
3803
3469
        return int(not result)
3804
3470
 
3805
3471
 
3806
3472
class cmd_version(Command):
3807
 
    __doc__ = """Show version of bzr."""
 
3473
    """Show version of bzr."""
3808
3474
 
3809
3475
    encoding_type = 'replace'
3810
3476
    takes_options = [
3821
3487
 
3822
3488
 
3823
3489
class cmd_rocks(Command):
3824
 
    __doc__ = """Statement of optimism."""
 
3490
    """Statement of optimism."""
3825
3491
 
3826
3492
    hidden = True
3827
3493
 
3828
3494
    @display_command
3829
3495
    def run(self):
3830
 
        self.outf.write("It sure does!\n")
 
3496
        print "It sure does!"
3831
3497
 
3832
3498
 
3833
3499
class cmd_find_merge_base(Command):
3834
 
    __doc__ = """Find and print a base revision for merging two branches."""
 
3500
    """Find and print a base revision for merging two branches."""
3835
3501
    # TODO: Options to specify revisions on either side, as if
3836
3502
    #       merging only part of the history.
3837
3503
    takes_args = ['branch', 'other']
3843
3509
 
3844
3510
        branch1 = Branch.open_containing(branch)[0]
3845
3511
        branch2 = Branch.open_containing(other)[0]
3846
 
        self.add_cleanup(branch1.lock_read().unlock)
3847
 
        self.add_cleanup(branch2.lock_read().unlock)
3848
 
        last1 = ensure_null(branch1.last_revision())
3849
 
        last2 = ensure_null(branch2.last_revision())
3850
 
 
3851
 
        graph = branch1.repository.get_graph(branch2.repository)
3852
 
        base_rev_id = graph.find_unique_lca(last1, last2)
3853
 
 
3854
 
        self.outf.write('merge base is revision %s\n' % base_rev_id)
 
3512
        branch1.lock_read()
 
3513
        try:
 
3514
            branch2.lock_read()
 
3515
            try:
 
3516
                last1 = ensure_null(branch1.last_revision())
 
3517
                last2 = ensure_null(branch2.last_revision())
 
3518
 
 
3519
                graph = branch1.repository.get_graph(branch2.repository)
 
3520
                base_rev_id = graph.find_unique_lca(last1, last2)
 
3521
 
 
3522
                print 'merge base is revision %s' % base_rev_id
 
3523
            finally:
 
3524
                branch2.unlock()
 
3525
        finally:
 
3526
            branch1.unlock()
3855
3527
 
3856
3528
 
3857
3529
class cmd_merge(Command):
3858
 
    __doc__ = """Perform a three-way merge.
 
3530
    """Perform a three-way merge.
3859
3531
 
3860
3532
    The source of the merge can be specified either in the form of a branch,
3861
3533
    or in the form of a path to a file containing a merge directive generated
3862
3534
    with bzr send. If neither is specified, the default is the upstream branch
3863
 
    or the branch most recently merged using --remember.  The source of the
3864
 
    merge may also be specified in the form of a path to a file in another
3865
 
    branch:  in this case, only the modifications to that file are merged into
3866
 
    the current working tree.
3867
 
 
3868
 
    When merging from a branch, by default bzr will try to merge in all new
3869
 
    work from the other branch, automatically determining an appropriate base
3870
 
    revision.  If this fails, you may need to give an explicit base.
3871
 
 
3872
 
    To pick a different ending revision, pass "--revision OTHER".  bzr will
3873
 
    try to merge in all new work up to and including revision OTHER.
3874
 
 
3875
 
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
3876
 
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
3877
 
    causes some revisions to be skipped, i.e. if the destination branch does
3878
 
    not already contain revision BASE, such a merge is commonly referred to as
3879
 
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
3880
 
    cherrypicks. The changes look like a normal commit, and the history of the
3881
 
    changes from the other branch is not stored in the commit.
3882
 
 
3883
 
    Revision numbers are always relative to the source branch.
 
3535
    or the branch most recently merged using --remember.
 
3536
 
 
3537
    When merging a branch, by default the tip will be merged. To pick a different
 
3538
    revision, pass --revision. If you specify two values, the first will be used as
 
3539
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
3540
    available revisions, like this is commonly referred to as "cherrypicking".
 
3541
 
 
3542
    Revision numbers are always relative to the branch being merged.
 
3543
 
 
3544
    By default, bzr will try to merge in all new work from the other
 
3545
    branch, automatically determining an appropriate base.  If this
 
3546
    fails, you may need to give an explicit base.
3884
3547
 
3885
3548
    Merge will do its best to combine the changes in two branches, but there
3886
3549
    are some kinds of problems only a human can fix.  When it encounters those,
3889
3552
 
3890
3553
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
3891
3554
 
3892
 
    If there is no default branch set, the first merge will set it (use
3893
 
    --no-remember to avoid settting it). After that, you can omit the branch
3894
 
    to use the default.  To change the default, use --remember. The value will
3895
 
    only be saved if the remote location can be accessed.
 
3555
    If there is no default branch set, the first merge will set it. After
 
3556
    that, you can omit the branch to use the default.  To change the
 
3557
    default, use --remember. The value will only be saved if the remote
 
3558
    location can be accessed.
3896
3559
 
3897
3560
    The results of the merge are placed into the destination working
3898
3561
    directory, where they can be reviewed (with bzr diff), tested, and then
3899
3562
    committed to record the result of the merge.
3900
3563
 
3901
3564
    merge refuses to run if there are any uncommitted changes, unless
3902
 
    --force is given.  If --force is given, then the changes from the source 
3903
 
    will be merged with the current working tree, including any uncommitted
3904
 
    changes in the tree.  The --force option can also be used to create a
3905
 
    merge revision which has more than two parents.
3906
 
 
3907
 
    If one would like to merge changes from the working tree of the other
3908
 
    branch without merging any committed revisions, the --uncommitted option
3909
 
    can be given.
 
3565
    --force is given.
3910
3566
 
3911
3567
    To select only some changes to merge, use "merge -i", which will prompt
3912
3568
    you to apply each diff hunk and file change, similar to "shelve".
3913
3569
 
3914
3570
    :Examples:
3915
 
        To merge all new revisions from bzr.dev::
 
3571
        To merge the latest revision from bzr.dev::
3916
3572
 
3917
3573
            bzr merge ../bzr.dev
3918
3574
 
3924
3580
 
3925
3581
            bzr merge -r 81..82 ../bzr.dev
3926
3582
 
3927
 
        To apply a merge directive contained in /tmp/merge::
 
3583
        To apply a merge directive contained in /tmp/merge:
3928
3584
 
3929
3585
            bzr merge /tmp/merge
3930
 
 
3931
 
        To create a merge revision with three parents from two branches
3932
 
        feature1a and feature1b:
3933
 
 
3934
 
            bzr merge ../feature1a
3935
 
            bzr merge ../feature1b --force
3936
 
            bzr commit -m 'revision with three parents'
3937
3586
    """
3938
3587
 
3939
3588
    encoding_type = 'exact'
3955
3604
                ' completely merged into the source, pull from the'
3956
3605
                ' source rather than merging.  When this happens,'
3957
3606
                ' you do not need to commit the result.'),
3958
 
        custom_help('directory',
 
3607
        Option('directory',
3959
3608
               help='Branch to merge into, '
3960
 
                    'rather than the one containing the working directory.'),
 
3609
                    'rather than the one containing the working directory.',
 
3610
               short_name='d',
 
3611
               type=unicode,
 
3612
               ),
3961
3613
        Option('preview', help='Instead of merging, show a diff of the'
3962
3614
               ' merge.'),
3963
3615
        Option('interactive', help='Select changes interactively.',
3965
3617
    ]
3966
3618
 
3967
3619
    def run(self, location=None, revision=None, force=False,
3968
 
            merge_type=None, show_base=False, reprocess=None, remember=None,
 
3620
            merge_type=None, show_base=False, reprocess=None, remember=False,
3969
3621
            uncommitted=False, pull=False,
3970
3622
            directory=None,
3971
3623
            preview=False,
3979
3631
        merger = None
3980
3632
        allow_pending = True
3981
3633
        verified = 'inapplicable'
3982
 
 
3983
3634
        tree = WorkingTree.open_containing(directory)[0]
3984
 
        if tree.branch.revno() == 0:
3985
 
            raise errors.BzrCommandError('Merging into empty branches not currently supported, '
3986
 
                                         'https://bugs.launchpad.net/bzr/+bug/308562')
3987
3635
 
 
3636
        # die as quickly as possible if there are uncommitted changes
3988
3637
        try:
3989
3638
            basis_tree = tree.revision_tree(tree.last_revision())
3990
3639
        except errors.NoSuchRevision:
3991
3640
            basis_tree = tree.basis_tree()
3992
 
 
3993
 
        # die as quickly as possible if there are uncommitted changes
3994
3641
        if not force:
3995
 
            if tree.has_changes():
 
3642
            if tree.has_changes(basis_tree):
3996
3643
                raise errors.UncommittedChanges(tree)
3997
3644
 
3998
3645
        view_info = _get_view_info_for_change_reporter(tree)
3999
3646
        change_reporter = delta._ChangeReporter(
4000
3647
            unversioned_filter=tree.is_ignored, view_info=view_info)
4001
 
        pb = ui.ui_factory.nested_progress_bar()
4002
 
        self.add_cleanup(pb.finished)
4003
 
        self.add_cleanup(tree.lock_write().unlock)
4004
 
        if location is not None:
4005
 
            try:
4006
 
                mergeable = bundle.read_mergeable_from_url(location,
4007
 
                    possible_transports=possible_transports)
4008
 
            except errors.NotABundle:
4009
 
                mergeable = None
 
3648
        cleanups = []
 
3649
        try:
 
3650
            pb = ui.ui_factory.nested_progress_bar()
 
3651
            cleanups.append(pb.finished)
 
3652
            tree.lock_write()
 
3653
            cleanups.append(tree.unlock)
 
3654
            if location is not None:
 
3655
                try:
 
3656
                    mergeable = bundle.read_mergeable_from_url(location,
 
3657
                        possible_transports=possible_transports)
 
3658
                except errors.NotABundle:
 
3659
                    mergeable = None
 
3660
                else:
 
3661
                    if uncommitted:
 
3662
                        raise errors.BzrCommandError('Cannot use --uncommitted'
 
3663
                            ' with bundles or merge directives.')
 
3664
 
 
3665
                    if revision is not None:
 
3666
                        raise errors.BzrCommandError(
 
3667
                            'Cannot use -r with merge directives or bundles')
 
3668
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
3669
                       mergeable, pb)
 
3670
 
 
3671
            if merger is None and uncommitted:
 
3672
                if revision is not None and len(revision) > 0:
 
3673
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
 
3674
                        ' --revision at the same time.')
 
3675
                merger = self.get_merger_from_uncommitted(tree, location, pb,
 
3676
                                                          cleanups)
 
3677
                allow_pending = False
 
3678
 
 
3679
            if merger is None:
 
3680
                merger, allow_pending = self._get_merger_from_branch(tree,
 
3681
                    location, revision, remember, possible_transports, pb)
 
3682
 
 
3683
            merger.merge_type = merge_type
 
3684
            merger.reprocess = reprocess
 
3685
            merger.show_base = show_base
 
3686
            self.sanity_check_merger(merger)
 
3687
            if (merger.base_rev_id == merger.other_rev_id and
 
3688
                merger.other_rev_id is not None):
 
3689
                note('Nothing to do.')
 
3690
                return 0
 
3691
            if pull:
 
3692
                if merger.interesting_files is not None:
 
3693
                    raise errors.BzrCommandError('Cannot pull individual files')
 
3694
                if (merger.base_rev_id == tree.last_revision()):
 
3695
                    result = tree.pull(merger.other_branch, False,
 
3696
                                       merger.other_rev_id)
 
3697
                    result.report(self.outf)
 
3698
                    return 0
 
3699
            merger.check_basis(False)
 
3700
            if preview:
 
3701
                return self._do_preview(merger, cleanups)
 
3702
            elif interactive:
 
3703
                return self._do_interactive(merger, cleanups)
4010
3704
            else:
4011
 
                if uncommitted:
4012
 
                    raise errors.BzrCommandError('Cannot use --uncommitted'
4013
 
                        ' with bundles or merge directives.')
4014
 
 
4015
 
                if revision is not None:
4016
 
                    raise errors.BzrCommandError(
4017
 
                        'Cannot use -r with merge directives or bundles')
4018
 
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
4019
 
                   mergeable, None)
4020
 
 
4021
 
        if merger is None and uncommitted:
4022
 
            if revision is not None and len(revision) > 0:
4023
 
                raise errors.BzrCommandError('Cannot use --uncommitted and'
4024
 
                    ' --revision at the same time.')
4025
 
            merger = self.get_merger_from_uncommitted(tree, location, None)
4026
 
            allow_pending = False
4027
 
 
4028
 
        if merger is None:
4029
 
            merger, allow_pending = self._get_merger_from_branch(tree,
4030
 
                location, revision, remember, possible_transports, None)
4031
 
 
4032
 
        merger.merge_type = merge_type
4033
 
        merger.reprocess = reprocess
4034
 
        merger.show_base = show_base
4035
 
        self.sanity_check_merger(merger)
4036
 
        if (merger.base_rev_id == merger.other_rev_id and
4037
 
            merger.other_rev_id is not None):
4038
 
            # check if location is a nonexistent file (and not a branch) to
4039
 
            # disambiguate the 'Nothing to do'
4040
 
            if merger.interesting_files:
4041
 
                if not merger.other_tree.has_filename(
4042
 
                    merger.interesting_files[0]):
4043
 
                    note("merger: " + str(merger))
4044
 
                    raise errors.PathsDoNotExist([location])
4045
 
            note('Nothing to do.')
4046
 
            return 0
4047
 
        if pull and not preview:
4048
 
            if merger.interesting_files is not None:
4049
 
                raise errors.BzrCommandError('Cannot pull individual files')
4050
 
            if (merger.base_rev_id == tree.last_revision()):
4051
 
                result = tree.pull(merger.other_branch, False,
4052
 
                                   merger.other_rev_id)
4053
 
                result.report(self.outf)
4054
 
                return 0
4055
 
        if merger.this_basis is None:
4056
 
            raise errors.BzrCommandError(
4057
 
                "This branch has no commits."
4058
 
                " (perhaps you would prefer 'bzr pull')")
4059
 
        if preview:
4060
 
            return self._do_preview(merger)
4061
 
        elif interactive:
4062
 
            return self._do_interactive(merger)
4063
 
        else:
4064
 
            return self._do_merge(merger, change_reporter, allow_pending,
4065
 
                                  verified)
4066
 
 
4067
 
    def _get_preview(self, merger):
 
3705
                return self._do_merge(merger, change_reporter, allow_pending,
 
3706
                                      verified)
 
3707
        finally:
 
3708
            for cleanup in reversed(cleanups):
 
3709
                cleanup()
 
3710
 
 
3711
    def _get_preview(self, merger, cleanups):
4068
3712
        tree_merger = merger.make_merger()
4069
3713
        tt = tree_merger.make_preview_transform()
4070
 
        self.add_cleanup(tt.finalize)
 
3714
        cleanups.append(tt.finalize)
4071
3715
        result_tree = tt.get_preview_tree()
4072
3716
        return result_tree
4073
3717
 
4074
 
    def _do_preview(self, merger):
 
3718
    def _do_preview(self, merger, cleanups):
4075
3719
        from bzrlib.diff import show_diff_trees
4076
 
        result_tree = self._get_preview(merger)
4077
 
        path_encoding = osutils.get_diff_header_encoding()
 
3720
        result_tree = self._get_preview(merger, cleanups)
4078
3721
        show_diff_trees(merger.this_tree, result_tree, self.outf,
4079
 
                        old_label='', new_label='',
4080
 
                        path_encoding=path_encoding)
 
3722
                        old_label='', new_label='')
4081
3723
 
4082
3724
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
4083
3725
        merger.change_reporter = change_reporter
4091
3733
        else:
4092
3734
            return 0
4093
3735
 
4094
 
    def _do_interactive(self, merger):
 
3736
    def _do_interactive(self, merger, cleanups):
4095
3737
        """Perform an interactive merge.
4096
3738
 
4097
3739
        This works by generating a preview tree of the merge, then using
4099
3741
        and the preview tree.
4100
3742
        """
4101
3743
        from bzrlib import shelf_ui
4102
 
        result_tree = self._get_preview(merger)
 
3744
        result_tree = self._get_preview(merger, cleanups)
4103
3745
        writer = bzrlib.option.diff_writer_registry.get()
4104
3746
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
4105
3747
                                   reporter=shelf_ui.ApplyReporter(),
4106
3748
                                   diff_writer=writer(sys.stdout))
4107
 
        try:
4108
 
            shelver.run()
4109
 
        finally:
4110
 
            shelver.finalize()
 
3749
        shelver.run()
4111
3750
 
4112
3751
    def sanity_check_merger(self, merger):
4113
3752
        if (merger.show_base and
4159
3798
        if other_revision_id is None:
4160
3799
            other_revision_id = _mod_revision.ensure_null(
4161
3800
                other_branch.last_revision())
4162
 
        # Remember where we merge from. We need to remember if:
4163
 
        # - user specify a location (and we don't merge from the parent
4164
 
        #   branch)
4165
 
        # - user ask to remember or there is no previous location set to merge
4166
 
        #   from and user didn't ask to *not* remember
4167
 
        if (user_location is not None
4168
 
            and ((remember
4169
 
                  or (remember is None
4170
 
                      and tree.branch.get_submit_branch() is None)))):
 
3801
        # Remember where we merge from
 
3802
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3803
             user_location is not None):
4171
3804
            tree.branch.set_submit_branch(other_branch.base)
4172
 
        # Merge tags (but don't set them in the master branch yet, the user
4173
 
        # might revert this merge).  Commit will propagate them.
4174
 
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
 
3805
        _merge_tags_if_possible(other_branch, tree.branch)
4175
3806
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4176
3807
            other_revision_id, base_revision_id, other_branch, base_branch)
4177
3808
        if other_path != '':
4181
3812
            allow_pending = True
4182
3813
        return merger, allow_pending
4183
3814
 
4184
 
    def get_merger_from_uncommitted(self, tree, location, pb):
 
3815
    def get_merger_from_uncommitted(self, tree, location, pb, cleanups):
4185
3816
        """Get a merger for uncommitted changes.
4186
3817
 
4187
3818
        :param tree: The tree the merger should apply to.
4188
3819
        :param location: The location containing uncommitted changes.
4189
3820
        :param pb: The progress bar to use for showing progress.
 
3821
        :param cleanups: A list of operations to perform to clean up the
 
3822
            temporary directories, unfinalized objects, etc.
4190
3823
        """
4191
3824
        location = self._select_branch_location(tree, location)[0]
4192
3825
        other_tree, other_path = WorkingTree.open_containing(location)
4244
3877
 
4245
3878
 
4246
3879
class cmd_remerge(Command):
4247
 
    __doc__ = """Redo a merge.
 
3880
    """Redo a merge.
4248
3881
 
4249
3882
    Use this if you want to try a different merge technique while resolving
4250
3883
    conflicts.  Some merge techniques are better than others, and remerge
4275
3908
 
4276
3909
    def run(self, file_list=None, merge_type=None, show_base=False,
4277
3910
            reprocess=False):
4278
 
        from bzrlib.conflicts import restore
4279
3911
        if merge_type is None:
4280
3912
            merge_type = _mod_merge.Merge3Merger
4281
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4282
 
        self.add_cleanup(tree.lock_write().unlock)
4283
 
        parents = tree.get_parent_ids()
4284
 
        if len(parents) != 2:
4285
 
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4286
 
                                         " merges.  Not cherrypicking or"
4287
 
                                         " multi-merges.")
4288
 
        repository = tree.branch.repository
4289
 
        interesting_ids = None
4290
 
        new_conflicts = []
4291
 
        conflicts = tree.conflicts()
4292
 
        if file_list is not None:
4293
 
            interesting_ids = set()
4294
 
            for filename in file_list:
4295
 
                file_id = tree.path2id(filename)
4296
 
                if file_id is None:
4297
 
                    raise errors.NotVersionedError(filename)
4298
 
                interesting_ids.add(file_id)
4299
 
                if tree.kind(file_id) != "directory":
4300
 
                    continue
 
3913
        tree, file_list = tree_files(file_list)
 
3914
        tree.lock_write()
 
3915
        try:
 
3916
            parents = tree.get_parent_ids()
 
3917
            if len(parents) != 2:
 
3918
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
 
3919
                                             " merges.  Not cherrypicking or"
 
3920
                                             " multi-merges.")
 
3921
            repository = tree.branch.repository
 
3922
            interesting_ids = None
 
3923
            new_conflicts = []
 
3924
            conflicts = tree.conflicts()
 
3925
            if file_list is not None:
 
3926
                interesting_ids = set()
 
3927
                for filename in file_list:
 
3928
                    file_id = tree.path2id(filename)
 
3929
                    if file_id is None:
 
3930
                        raise errors.NotVersionedError(filename)
 
3931
                    interesting_ids.add(file_id)
 
3932
                    if tree.kind(file_id) != "directory":
 
3933
                        continue
4301
3934
 
4302
 
                for name, ie in tree.inventory.iter_entries(file_id):
4303
 
                    interesting_ids.add(ie.file_id)
4304
 
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4305
 
        else:
4306
 
            # Remerge only supports resolving contents conflicts
4307
 
            allowed_conflicts = ('text conflict', 'contents conflict')
4308
 
            restore_files = [c.path for c in conflicts
4309
 
                             if c.typestring in allowed_conflicts]
4310
 
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4311
 
        tree.set_conflicts(ConflictList(new_conflicts))
4312
 
        if file_list is not None:
4313
 
            restore_files = file_list
4314
 
        for filename in restore_files:
 
3935
                    for name, ie in tree.inventory.iter_entries(file_id):
 
3936
                        interesting_ids.add(ie.file_id)
 
3937
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
3938
            else:
 
3939
                # Remerge only supports resolving contents conflicts
 
3940
                allowed_conflicts = ('text conflict', 'contents conflict')
 
3941
                restore_files = [c.path for c in conflicts
 
3942
                                 if c.typestring in allowed_conflicts]
 
3943
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
 
3944
            tree.set_conflicts(ConflictList(new_conflicts))
 
3945
            if file_list is not None:
 
3946
                restore_files = file_list
 
3947
            for filename in restore_files:
 
3948
                try:
 
3949
                    restore(tree.abspath(filename))
 
3950
                except errors.NotConflicted:
 
3951
                    pass
 
3952
            # Disable pending merges, because the file texts we are remerging
 
3953
            # have not had those merges performed.  If we use the wrong parents
 
3954
            # list, we imply that the working tree text has seen and rejected
 
3955
            # all the changes from the other tree, when in fact those changes
 
3956
            # have not yet been seen.
 
3957
            pb = ui.ui_factory.nested_progress_bar()
 
3958
            tree.set_parent_ids(parents[:1])
4315
3959
            try:
4316
 
                restore(tree.abspath(filename))
4317
 
            except errors.NotConflicted:
4318
 
                pass
4319
 
        # Disable pending merges, because the file texts we are remerging
4320
 
        # have not had those merges performed.  If we use the wrong parents
4321
 
        # list, we imply that the working tree text has seen and rejected
4322
 
        # all the changes from the other tree, when in fact those changes
4323
 
        # have not yet been seen.
4324
 
        tree.set_parent_ids(parents[:1])
4325
 
        try:
4326
 
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4327
 
            merger.interesting_ids = interesting_ids
4328
 
            merger.merge_type = merge_type
4329
 
            merger.show_base = show_base
4330
 
            merger.reprocess = reprocess
4331
 
            conflicts = merger.do_merge()
 
3960
                merger = _mod_merge.Merger.from_revision_ids(pb,
 
3961
                                                             tree, parents[1])
 
3962
                merger.interesting_ids = interesting_ids
 
3963
                merger.merge_type = merge_type
 
3964
                merger.show_base = show_base
 
3965
                merger.reprocess = reprocess
 
3966
                conflicts = merger.do_merge()
 
3967
            finally:
 
3968
                tree.set_parent_ids(parents)
 
3969
                pb.finished()
4332
3970
        finally:
4333
 
            tree.set_parent_ids(parents)
 
3971
            tree.unlock()
4334
3972
        if conflicts > 0:
4335
3973
            return 1
4336
3974
        else:
4338
3976
 
4339
3977
 
4340
3978
class cmd_revert(Command):
4341
 
    __doc__ = """Revert files to a previous revision.
 
3979
    """Revert files to a previous revision.
4342
3980
 
4343
3981
    Giving a list of files will revert only those files.  Otherwise, all files
4344
3982
    will be reverted.  If the revision is not specified with '--revision', the
4345
3983
    last committed revision is used.
4346
3984
 
4347
3985
    To remove only some changes, without reverting to a prior version, use
4348
 
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
4349
 
    will remove the changes introduced by the second last commit (-2), without
4350
 
    affecting the changes introduced by the last commit (-1).  To remove
4351
 
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
3986
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
3987
    changes introduced by -2, without affecting the changes introduced by -1.
 
3988
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4352
3989
 
4353
3990
    By default, any files that have been manually changed will be backed up
4354
3991
    first.  (Files changed only by merge are not backed up.)  Backup files have
4359
3996
    name.  If you name a directory, all the contents of that directory will be
4360
3997
    reverted.
4361
3998
 
4362
 
    If you have newly added files since the target revision, they will be
4363
 
    removed.  If the files to be removed have been changed, backups will be
4364
 
    created as above.  Directories containing unknown files will not be
4365
 
    deleted.
 
3999
    Any files that have been newly added since that revision will be deleted,
 
4000
    with a backup kept if appropriate.  Directories containing unknown files
 
4001
    will not be deleted.
4366
4002
 
4367
 
    The working tree contains a list of revisions that have been merged but
4368
 
    not yet committed. These revisions will be included as additional parents
4369
 
    of the next commit.  Normally, using revert clears that list as well as
4370
 
    reverting the files.  If any files are specified, revert leaves the list
4371
 
    of uncommitted merges alone and reverts only the files.  Use ``bzr revert
4372
 
    .`` in the tree root to revert all files but keep the recorded merges,
4373
 
    and ``bzr revert --forget-merges`` to clear the pending merge list without
 
4003
    The working tree contains a list of pending merged revisions, which will
 
4004
    be included as parents in the next commit.  Normally, revert clears that
 
4005
    list as well as reverting the files.  If any files are specified, revert
 
4006
    leaves the pending merge list alone and reverts only the files.  Use "bzr
 
4007
    revert ." in the tree root to revert all files but keep the merge record,
 
4008
    and "bzr revert --forget-merges" to clear the pending merge list without
4374
4009
    reverting any files.
4375
 
 
4376
 
    Using "bzr revert --forget-merges", it is possible to apply all of the
4377
 
    changes from a branch in a single revision.  To do this, perform the merge
4378
 
    as desired.  Then doing revert with the "--forget-merges" option will keep
4379
 
    the content of the tree as it was, but it will clear the list of pending
4380
 
    merges.  The next commit will then contain all of the changes that are
4381
 
    present in the other branch, but without any other parent revisions.
4382
 
    Because this technique forgets where these changes originated, it may
4383
 
    cause additional conflicts on later merges involving the same source and
4384
 
    target branches.
4385
4010
    """
4386
4011
 
4387
 
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4012
    _see_also = ['cat', 'export']
4388
4013
    takes_options = [
4389
4014
        'revision',
4390
4015
        Option('no-backup', "Do not save backups of reverted files."),
4395
4020
 
4396
4021
    def run(self, revision=None, no_backup=False, file_list=None,
4397
4022
            forget_merges=None):
4398
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4399
 
        self.add_cleanup(tree.lock_tree_write().unlock)
4400
 
        if forget_merges:
4401
 
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4402
 
        else:
4403
 
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4023
        tree, file_list = tree_files(file_list)
 
4024
        tree.lock_write()
 
4025
        try:
 
4026
            if forget_merges:
 
4027
                tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4028
            else:
 
4029
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4030
        finally:
 
4031
            tree.unlock()
4404
4032
 
4405
4033
    @staticmethod
4406
4034
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
4407
4035
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4408
 
        tree.revert(file_list, rev_tree, not no_backup, None,
4409
 
            report_changes=True)
 
4036
        pb = ui.ui_factory.nested_progress_bar()
 
4037
        try:
 
4038
            tree.revert(file_list, rev_tree, not no_backup, pb,
 
4039
                report_changes=True)
 
4040
        finally:
 
4041
            pb.finished()
4410
4042
 
4411
4043
 
4412
4044
class cmd_assert_fail(Command):
4413
 
    __doc__ = """Test reporting of assertion failures"""
 
4045
    """Test reporting of assertion failures"""
4414
4046
    # intended just for use in testing
4415
4047
 
4416
4048
    hidden = True
4420
4052
 
4421
4053
 
4422
4054
class cmd_help(Command):
4423
 
    __doc__ = """Show help on a command or other topic.
 
4055
    """Show help on a command or other topic.
4424
4056
    """
4425
4057
 
4426
4058
    _see_also = ['topics']
4439
4071
 
4440
4072
 
4441
4073
class cmd_shell_complete(Command):
4442
 
    __doc__ = """Show appropriate completions for context.
 
4074
    """Show appropriate completions for context.
4443
4075
 
4444
4076
    For a list of all available commands, say 'bzr shell-complete'.
4445
4077
    """
4454
4086
 
4455
4087
 
4456
4088
class cmd_missing(Command):
4457
 
    __doc__ = """Show unmerged/unpulled revisions between two branches.
 
4089
    """Show unmerged/unpulled revisions between two branches.
4458
4090
 
4459
4091
    OTHER_BRANCH may be local or remote.
4460
4092
 
4461
4093
    To filter on a range of revisions, you can use the command -r begin..end
4462
4094
    -r revision requests a specific revision, -r ..end or -r begin.. are
4463
4095
    also valid.
4464
 
            
4465
 
    :Exit values:
4466
 
        1 - some missing revisions
4467
 
        0 - no missing revisions
4468
4096
 
4469
4097
    :Examples:
4470
4098
 
4491
4119
    _see_also = ['merge', 'pull']
4492
4120
    takes_args = ['other_branch?']
4493
4121
    takes_options = [
4494
 
        'directory',
4495
4122
        Option('reverse', 'Reverse the order of revisions.'),
4496
4123
        Option('mine-only',
4497
4124
               'Display changes in the local branch only.'),
4519
4146
            theirs_only=False,
4520
4147
            log_format=None, long=False, short=False, line=False,
4521
4148
            show_ids=False, verbose=False, this=False, other=False,
4522
 
            include_merges=False, revision=None, my_revision=None,
4523
 
            directory=u'.'):
 
4149
            include_merges=False, revision=None, my_revision=None):
4524
4150
        from bzrlib.missing import find_unmerged, iter_log_revisions
4525
4151
        def message(s):
4526
4152
            if not is_quiet():
4539
4165
        elif theirs_only:
4540
4166
            restrict = 'remote'
4541
4167
 
4542
 
        local_branch = Branch.open_containing(directory)[0]
4543
 
        self.add_cleanup(local_branch.lock_read().unlock)
4544
 
 
 
4168
        local_branch = Branch.open_containing(u".")[0]
4545
4169
        parent = local_branch.get_parent()
4546
4170
        if other_branch is None:
4547
4171
            other_branch = parent
4556
4180
        remote_branch = Branch.open(other_branch)
4557
4181
        if remote_branch.base == local_branch.base:
4558
4182
            remote_branch = local_branch
4559
 
        else:
4560
 
            self.add_cleanup(remote_branch.lock_read().unlock)
4561
4183
 
4562
4184
        local_revid_range = _revision_range_to_revid_range(
4563
4185
            _get_revision_range(my_revision, local_branch,
4567
4189
            _get_revision_range(revision,
4568
4190
                remote_branch, self.name()))
4569
4191
 
4570
 
        local_extra, remote_extra = find_unmerged(
4571
 
            local_branch, remote_branch, restrict,
4572
 
            backward=not reverse,
4573
 
            include_merges=include_merges,
4574
 
            local_revid_range=local_revid_range,
4575
 
            remote_revid_range=remote_revid_range)
4576
 
 
4577
 
        if log_format is None:
4578
 
            registry = log.log_formatter_registry
4579
 
            log_format = registry.get_default(local_branch)
4580
 
        lf = log_format(to_file=self.outf,
4581
 
                        show_ids=show_ids,
4582
 
                        show_timezone='original')
4583
 
 
4584
 
        status_code = 0
4585
 
        if local_extra and not theirs_only:
4586
 
            message("You have %d extra revision(s):\n" %
4587
 
                len(local_extra))
4588
 
            for revision in iter_log_revisions(local_extra,
4589
 
                                local_branch.repository,
4590
 
                                verbose):
4591
 
                lf.log_revision(revision)
4592
 
            printed_local = True
4593
 
            status_code = 1
4594
 
        else:
4595
 
            printed_local = False
4596
 
 
4597
 
        if remote_extra and not mine_only:
4598
 
            if printed_local is True:
4599
 
                message("\n\n\n")
4600
 
            message("You are missing %d revision(s):\n" %
4601
 
                len(remote_extra))
4602
 
            for revision in iter_log_revisions(remote_extra,
4603
 
                                remote_branch.repository,
4604
 
                                verbose):
4605
 
                lf.log_revision(revision)
4606
 
            status_code = 1
4607
 
 
4608
 
        if mine_only and not local_extra:
4609
 
            # We checked local, and found nothing extra
4610
 
            message('This branch is up to date.\n')
4611
 
        elif theirs_only and not remote_extra:
4612
 
            # We checked remote, and found nothing extra
4613
 
            message('Other branch is up to date.\n')
4614
 
        elif not (mine_only or theirs_only or local_extra or
4615
 
                  remote_extra):
4616
 
            # We checked both branches, and neither one had extra
4617
 
            # revisions
4618
 
            message("Branches are up to date.\n")
4619
 
        self.cleanup_now()
 
4192
        local_branch.lock_read()
 
4193
        try:
 
4194
            remote_branch.lock_read()
 
4195
            try:
 
4196
                local_extra, remote_extra = find_unmerged(
 
4197
                    local_branch, remote_branch, restrict,
 
4198
                    backward=not reverse,
 
4199
                    include_merges=include_merges,
 
4200
                    local_revid_range=local_revid_range,
 
4201
                    remote_revid_range=remote_revid_range)
 
4202
 
 
4203
                if log_format is None:
 
4204
                    registry = log.log_formatter_registry
 
4205
                    log_format = registry.get_default(local_branch)
 
4206
                lf = log_format(to_file=self.outf,
 
4207
                                show_ids=show_ids,
 
4208
                                show_timezone='original')
 
4209
 
 
4210
                status_code = 0
 
4211
                if local_extra and not theirs_only:
 
4212
                    message("You have %d extra revision(s):\n" %
 
4213
                        len(local_extra))
 
4214
                    for revision in iter_log_revisions(local_extra,
 
4215
                                        local_branch.repository,
 
4216
                                        verbose):
 
4217
                        lf.log_revision(revision)
 
4218
                    printed_local = True
 
4219
                    status_code = 1
 
4220
                else:
 
4221
                    printed_local = False
 
4222
 
 
4223
                if remote_extra and not mine_only:
 
4224
                    if printed_local is True:
 
4225
                        message("\n\n\n")
 
4226
                    message("You are missing %d revision(s):\n" %
 
4227
                        len(remote_extra))
 
4228
                    for revision in iter_log_revisions(remote_extra,
 
4229
                                        remote_branch.repository,
 
4230
                                        verbose):
 
4231
                        lf.log_revision(revision)
 
4232
                    status_code = 1
 
4233
 
 
4234
                if mine_only and not local_extra:
 
4235
                    # We checked local, and found nothing extra
 
4236
                    message('This branch is up to date.\n')
 
4237
                elif theirs_only and not remote_extra:
 
4238
                    # We checked remote, and found nothing extra
 
4239
                    message('Other branch is up to date.\n')
 
4240
                elif not (mine_only or theirs_only or local_extra or
 
4241
                          remote_extra):
 
4242
                    # We checked both branches, and neither one had extra
 
4243
                    # revisions
 
4244
                    message("Branches are up to date.\n")
 
4245
            finally:
 
4246
                remote_branch.unlock()
 
4247
        finally:
 
4248
            local_branch.unlock()
4620
4249
        if not status_code and parent is None and other_branch is not None:
4621
 
            self.add_cleanup(local_branch.lock_write().unlock)
4622
 
            # handle race conditions - a parent might be set while we run.
4623
 
            if local_branch.get_parent() is None:
4624
 
                local_branch.set_parent(remote_branch.base)
 
4250
            local_branch.lock_write()
 
4251
            try:
 
4252
                # handle race conditions - a parent might be set while we run.
 
4253
                if local_branch.get_parent() is None:
 
4254
                    local_branch.set_parent(remote_branch.base)
 
4255
            finally:
 
4256
                local_branch.unlock()
4625
4257
        return status_code
4626
4258
 
4627
4259
 
4628
4260
class cmd_pack(Command):
4629
 
    __doc__ = """Compress the data within a repository.
4630
 
 
4631
 
    This operation compresses the data within a bazaar repository. As
4632
 
    bazaar supports automatic packing of repository, this operation is
4633
 
    normally not required to be done manually.
4634
 
 
4635
 
    During the pack operation, bazaar takes a backup of existing repository
4636
 
    data, i.e. pack files. This backup is eventually removed by bazaar
4637
 
    automatically when it is safe to do so. To save disk space by removing
4638
 
    the backed up pack files, the --clean-obsolete-packs option may be
4639
 
    used.
4640
 
 
4641
 
    Warning: If you use --clean-obsolete-packs and your machine crashes
4642
 
    during or immediately after repacking, you may be left with a state
4643
 
    where the deletion has been written to disk but the new packs have not
4644
 
    been. In this case the repository may be unusable.
4645
 
    """
 
4261
    """Compress the data within a repository."""
4646
4262
 
4647
4263
    _see_also = ['repositories']
4648
4264
    takes_args = ['branch_or_repo?']
4649
 
    takes_options = [
4650
 
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4651
 
        ]
4652
4265
 
4653
 
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
 
4266
    def run(self, branch_or_repo='.'):
4654
4267
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4655
4268
        try:
4656
4269
            branch = dir.open_branch()
4657
4270
            repository = branch.repository
4658
4271
        except errors.NotBranchError:
4659
4272
            repository = dir.open_repository()
4660
 
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
4273
        repository.pack()
4661
4274
 
4662
4275
 
4663
4276
class cmd_plugins(Command):
4664
 
    __doc__ = """List the installed plugins.
 
4277
    """List the installed plugins.
4665
4278
 
4666
4279
    This command displays the list of installed plugins including
4667
4280
    version of plugin and a short description of each.
4674
4287
    adding new commands, providing additional network transports and
4675
4288
    customizing log output.
4676
4289
 
4677
 
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4678
 
    for further information on plugins including where to find them and how to
4679
 
    install them. Instructions are also provided there on how to write new
4680
 
    plugins using the Python programming language.
 
4290
    See the Bazaar web site, http://bazaar-vcs.org, for further
 
4291
    information on plugins including where to find them and how to
 
4292
    install them. Instructions are also provided there on how to
 
4293
    write new plugins using the Python programming language.
4681
4294
    """
4682
4295
    takes_options = ['verbose']
4683
4296
 
4684
4297
    @display_command
4685
4298
    def run(self, verbose=False):
4686
 
        from bzrlib import plugin
4687
 
        # Don't give writelines a generator as some codecs don't like that
4688
 
        self.outf.writelines(
4689
 
            list(plugin.describe_plugins(show_paths=verbose)))
 
4299
        import bzrlib.plugin
 
4300
        from inspect import getdoc
 
4301
        result = []
 
4302
        for name, plugin in bzrlib.plugin.plugins().items():
 
4303
            version = plugin.__version__
 
4304
            if version == 'unknown':
 
4305
                version = ''
 
4306
            name_ver = '%s %s' % (name, version)
 
4307
            d = getdoc(plugin.module)
 
4308
            if d:
 
4309
                doc = d.split('\n')[0]
 
4310
            else:
 
4311
                doc = '(no description)'
 
4312
            result.append((name_ver, doc, plugin.path()))
 
4313
        for name_ver, doc, path in sorted(result):
 
4314
            print name_ver
 
4315
            print '   ', doc
 
4316
            if verbose:
 
4317
                print '   ', path
 
4318
            print
4690
4319
 
4691
4320
 
4692
4321
class cmd_testament(Command):
4693
 
    __doc__ = """Show testament (signing-form) of a revision."""
 
4322
    """Show testament (signing-form) of a revision."""
4694
4323
    takes_options = [
4695
4324
            'revision',
4696
4325
            Option('long', help='Produce long-format testament.'),
4708
4337
            b = Branch.open_containing(branch)[0]
4709
4338
        else:
4710
4339
            b = Branch.open(branch)
4711
 
        self.add_cleanup(b.lock_read().unlock)
4712
 
        if revision is None:
4713
 
            rev_id = b.last_revision()
4714
 
        else:
4715
 
            rev_id = revision[0].as_revision_id(b)
4716
 
        t = testament_class.from_revision(b.repository, rev_id)
4717
 
        if long:
4718
 
            sys.stdout.writelines(t.as_text_lines())
4719
 
        else:
4720
 
            sys.stdout.write(t.as_short_text())
 
4340
        b.lock_read()
 
4341
        try:
 
4342
            if revision is None:
 
4343
                rev_id = b.last_revision()
 
4344
            else:
 
4345
                rev_id = revision[0].as_revision_id(b)
 
4346
            t = testament_class.from_revision(b.repository, rev_id)
 
4347
            if long:
 
4348
                sys.stdout.writelines(t.as_text_lines())
 
4349
            else:
 
4350
                sys.stdout.write(t.as_short_text())
 
4351
        finally:
 
4352
            b.unlock()
4721
4353
 
4722
4354
 
4723
4355
class cmd_annotate(Command):
4724
 
    __doc__ = """Show the origin of each line in a file.
 
4356
    """Show the origin of each line in a file.
4725
4357
 
4726
4358
    This prints out the given file with an annotation on the left side
4727
4359
    indicating which revision, author and date introduced the change.
4738
4370
                     Option('long', help='Show commit date in annotations.'),
4739
4371
                     'revision',
4740
4372
                     'show-ids',
4741
 
                     'directory',
4742
4373
                     ]
4743
4374
    encoding_type = 'exact'
4744
4375
 
4745
4376
    @display_command
4746
4377
    def run(self, filename, all=False, long=False, revision=None,
4747
 
            show_ids=False, directory=None):
4748
 
        from bzrlib.annotate import (
4749
 
            annotate_file_tree,
4750
 
            )
 
4378
            show_ids=False):
 
4379
        from bzrlib.annotate import annotate_file, annotate_file_tree
4751
4380
        wt, branch, relpath = \
4752
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4381
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
4753
4382
        if wt is not None:
4754
 
            self.add_cleanup(wt.lock_read().unlock)
4755
 
        else:
4756
 
            self.add_cleanup(branch.lock_read().unlock)
4757
 
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4758
 
        self.add_cleanup(tree.lock_read().unlock)
4759
 
        if wt is not None and revision is None:
4760
 
            file_id = wt.path2id(relpath)
4761
 
        else:
4762
 
            file_id = tree.path2id(relpath)
4763
 
        if file_id is None:
4764
 
            raise errors.NotVersionedError(filename)
4765
 
        if wt is not None and revision is None:
4766
 
            # If there is a tree and we're not annotating historical
4767
 
            # versions, annotate the working tree's content.
4768
 
            annotate_file_tree(wt, file_id, self.outf, long, all,
4769
 
                show_ids=show_ids)
4770
 
        else:
4771
 
            annotate_file_tree(tree, file_id, self.outf, long, all,
4772
 
                show_ids=show_ids, branch=branch)
 
4383
            wt.lock_read()
 
4384
        else:
 
4385
            branch.lock_read()
 
4386
        try:
 
4387
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
 
4388
            if wt is not None:
 
4389
                file_id = wt.path2id(relpath)
 
4390
            else:
 
4391
                file_id = tree.path2id(relpath)
 
4392
            if file_id is None:
 
4393
                raise errors.NotVersionedError(filename)
 
4394
            file_version = tree.inventory[file_id].revision
 
4395
            if wt is not None and revision is None:
 
4396
                # If there is a tree and we're not annotating historical
 
4397
                # versions, annotate the working tree's content.
 
4398
                annotate_file_tree(wt, file_id, self.outf, long, all,
 
4399
                    show_ids=show_ids)
 
4400
            else:
 
4401
                annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4402
                              show_ids=show_ids)
 
4403
        finally:
 
4404
            if wt is not None:
 
4405
                wt.unlock()
 
4406
            else:
 
4407
                branch.unlock()
4773
4408
 
4774
4409
 
4775
4410
class cmd_re_sign(Command):
4776
 
    __doc__ = """Create a digital signature for an existing revision."""
 
4411
    """Create a digital signature for an existing revision."""
4777
4412
    # TODO be able to replace existing ones.
4778
4413
 
4779
4414
    hidden = True # is this right ?
4780
4415
    takes_args = ['revision_id*']
4781
 
    takes_options = ['directory', 'revision']
 
4416
    takes_options = ['revision']
4782
4417
 
4783
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
4418
    def run(self, revision_id_list=None, revision=None):
4784
4419
        if revision_id_list is not None and revision is not None:
4785
4420
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4786
4421
        if revision_id_list is None and revision is None:
4787
4422
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4788
 
        b = WorkingTree.open_containing(directory)[0].branch
4789
 
        self.add_cleanup(b.lock_write().unlock)
4790
 
        return self._run(b, revision_id_list, revision)
 
4423
        b = WorkingTree.open_containing(u'.')[0].branch
 
4424
        b.lock_write()
 
4425
        try:
 
4426
            return self._run(b, revision_id_list, revision)
 
4427
        finally:
 
4428
            b.unlock()
4791
4429
 
4792
4430
    def _run(self, b, revision_id_list, revision):
4793
4431
        import bzrlib.gpg as gpg
4838
4476
 
4839
4477
 
4840
4478
class cmd_bind(Command):
4841
 
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
4842
 
    If no branch is supplied, rebind to the last bound location.
 
4479
    """Convert the current branch into a checkout of the supplied branch.
4843
4480
 
4844
4481
    Once converted into a checkout, commits must succeed on the master branch
4845
4482
    before they will be applied to the local branch.
4846
4483
 
4847
4484
    Bound branches use the nickname of its master branch unless it is set
4848
 
    locally, in which case binding will update the local nickname to be
 
4485
    locally, in which case binding will update the the local nickname to be
4849
4486
    that of the master.
4850
4487
    """
4851
4488
 
4852
4489
    _see_also = ['checkouts', 'unbind']
4853
4490
    takes_args = ['location?']
4854
 
    takes_options = ['directory']
 
4491
    takes_options = []
4855
4492
 
4856
 
    def run(self, location=None, directory=u'.'):
4857
 
        b, relpath = Branch.open_containing(directory)
 
4493
    def run(self, location=None):
 
4494
        b, relpath = Branch.open_containing(u'.')
4858
4495
        if location is None:
4859
4496
            try:
4860
4497
                location = b.get_old_bound_location()
4863
4500
                    'This format does not remember old locations.')
4864
4501
            else:
4865
4502
                if location is None:
4866
 
                    if b.get_bound_location() is not None:
4867
 
                        raise errors.BzrCommandError('Branch is already bound')
4868
 
                    else:
4869
 
                        raise errors.BzrCommandError('No location supplied '
4870
 
                            'and no previous location known')
 
4503
                    raise errors.BzrCommandError('No location supplied and no '
 
4504
                        'previous location known')
4871
4505
        b_other = Branch.open(location)
4872
4506
        try:
4873
4507
            b.bind(b_other)
4879
4513
 
4880
4514
 
4881
4515
class cmd_unbind(Command):
4882
 
    __doc__ = """Convert the current checkout into a regular branch.
 
4516
    """Convert the current checkout into a regular branch.
4883
4517
 
4884
4518
    After unbinding, the local branch is considered independent and subsequent
4885
4519
    commits will be local only.
4887
4521
 
4888
4522
    _see_also = ['checkouts', 'bind']
4889
4523
    takes_args = []
4890
 
    takes_options = ['directory']
 
4524
    takes_options = []
4891
4525
 
4892
 
    def run(self, directory=u'.'):
4893
 
        b, relpath = Branch.open_containing(directory)
 
4526
    def run(self):
 
4527
        b, relpath = Branch.open_containing(u'.')
4894
4528
        if not b.unbind():
4895
4529
            raise errors.BzrCommandError('Local branch is not bound')
4896
4530
 
4897
4531
 
4898
4532
class cmd_uncommit(Command):
4899
 
    __doc__ = """Remove the last committed revision.
 
4533
    """Remove the last committed revision.
4900
4534
 
4901
4535
    --verbose will print out what is being removed.
4902
4536
    --dry-run will go through all the motions, but not actually
4942
4576
            b = control.open_branch()
4943
4577
 
4944
4578
        if tree is not None:
4945
 
            self.add_cleanup(tree.lock_write().unlock)
 
4579
            tree.lock_write()
4946
4580
        else:
4947
 
            self.add_cleanup(b.lock_write().unlock)
4948
 
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
 
4581
            b.lock_write()
 
4582
        try:
 
4583
            return self._run(b, tree, dry_run, verbose, revision, force,
 
4584
                             local=local)
 
4585
        finally:
 
4586
            if tree is not None:
 
4587
                tree.unlock()
 
4588
            else:
 
4589
                b.unlock()
4949
4590
 
4950
4591
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4951
4592
        from bzrlib.log import log_formatter, show_log
4983
4624
                 end_revision=last_revno)
4984
4625
 
4985
4626
        if dry_run:
4986
 
            self.outf.write('Dry-run, pretending to remove'
4987
 
                            ' the above revisions.\n')
 
4627
            print 'Dry-run, pretending to remove the above revisions.'
 
4628
            if not force:
 
4629
                val = raw_input('Press <enter> to continue')
4988
4630
        else:
4989
 
            self.outf.write('The above revision(s) will be removed.\n')
4990
 
 
4991
 
        if not force:
4992
 
            if not ui.ui_factory.confirm_action(
4993
 
                    u'Uncommit these revisions',
4994
 
                    'bzrlib.builtins.uncommit',
4995
 
                    {}):
4996
 
                self.outf.write('Canceled\n')
4997
 
                return 0
 
4631
            print 'The above revision(s) will be removed.'
 
4632
            if not force:
 
4633
                val = raw_input('Are you sure [y/N]? ')
 
4634
                if val.lower() not in ('y', 'yes'):
 
4635
                    print 'Canceled'
 
4636
                    return 0
4998
4637
 
4999
4638
        mutter('Uncommitting from {%s} to {%s}',
5000
4639
               last_rev_id, rev_id)
5001
4640
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
5002
4641
                 revno=revno, local=local)
5003
 
        self.outf.write('You can restore the old tip by running:\n'
5004
 
             '  bzr pull . -r revid:%s\n' % last_rev_id)
 
4642
        note('You can restore the old tip by running:\n'
 
4643
             '  bzr pull . -r revid:%s', last_rev_id)
5005
4644
 
5006
4645
 
5007
4646
class cmd_break_lock(Command):
5008
 
    __doc__ = """Break a dead lock.
5009
 
 
5010
 
    This command breaks a lock on a repository, branch, working directory or
5011
 
    config file.
 
4647
    """Break a dead lock on a repository, branch or working directory.
5012
4648
 
5013
4649
    CAUTION: Locks should only be broken when you are sure that the process
5014
4650
    holding the lock has been stopped.
5015
4651
 
5016
 
    You can get information on what locks are open via the 'bzr info
5017
 
    [location]' command.
 
4652
    You can get information on what locks are open via the 'bzr info' command.
5018
4653
 
5019
4654
    :Examples:
5020
4655
        bzr break-lock
5021
 
        bzr break-lock bzr+ssh://example.com/bzr/foo
5022
 
        bzr break-lock --conf ~/.bazaar
5023
4656
    """
5024
 
 
5025
4657
    takes_args = ['location?']
5026
 
    takes_options = [
5027
 
        Option('config',
5028
 
               help='LOCATION is the directory where the config lock is.'),
5029
 
        Option('force',
5030
 
            help='Do not ask for confirmation before breaking the lock.'),
5031
 
        ]
5032
4658
 
5033
 
    def run(self, location=None, config=False, force=False):
 
4659
    def run(self, location=None, show=False):
5034
4660
        if location is None:
5035
4661
            location = u'.'
5036
 
        if force:
5037
 
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5038
 
                None,
5039
 
                {'bzrlib.lockdir.break': True})
5040
 
        if config:
5041
 
            conf = _mod_config.LockableConfig(file_name=location)
5042
 
            conf.break_lock()
5043
 
        else:
5044
 
            control, relpath = bzrdir.BzrDir.open_containing(location)
5045
 
            try:
5046
 
                control.break_lock()
5047
 
            except NotImplementedError:
5048
 
                pass
 
4662
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4663
        try:
 
4664
            control.break_lock()
 
4665
        except NotImplementedError:
 
4666
            pass
5049
4667
 
5050
4668
 
5051
4669
class cmd_wait_until_signalled(Command):
5052
 
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4670
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
5053
4671
 
5054
4672
    This just prints a line to signal when it is ready, then blocks on stdin.
5055
4673
    """
5063
4681
 
5064
4682
 
5065
4683
class cmd_serve(Command):
5066
 
    __doc__ = """Run the bzr server."""
 
4684
    """Run the bzr server."""
5067
4685
 
5068
4686
    aliases = ['server']
5069
4687
 
5070
4688
    takes_options = [
5071
4689
        Option('inet',
5072
4690
               help='Serve on stdin/out for use from inetd or sshd.'),
5073
 
        RegistryOption('protocol',
5074
 
               help="Protocol to serve.",
 
4691
        RegistryOption('protocol', 
 
4692
               help="Protocol to serve.", 
5075
4693
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
5076
4694
               value_switches=True),
5077
4695
        Option('port',
5080
4698
                    'result in a dynamically allocated port.  The default port '
5081
4699
                    'depends on the protocol.',
5082
4700
               type=str),
5083
 
        custom_help('directory',
5084
 
               help='Serve contents of this directory.'),
 
4701
        Option('directory',
 
4702
               help='Serve contents of this directory.',
 
4703
               type=unicode),
5085
4704
        Option('allow-writes',
5086
4705
               help='By default the server is a readonly server.  Supplying '
5087
4706
                    '--allow-writes enables write access to the contents of '
5088
 
                    'the served directory and below.  Note that ``bzr serve`` '
5089
 
                    'does not perform authentication, so unless some form of '
5090
 
                    'external authentication is arranged supplying this '
5091
 
                    'option leads to global uncontrolled write access to your '
5092
 
                    'file system.'
 
4707
                    'the served directory and below.'
5093
4708
                ),
5094
4709
        ]
5095
4710
 
5114
4729
 
5115
4730
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
5116
4731
            protocol=None):
5117
 
        from bzrlib import transport
 
4732
        from bzrlib.transport import get_transport, transport_server_registry
5118
4733
        if directory is None:
5119
4734
            directory = os.getcwd()
5120
4735
        if protocol is None:
5121
 
            protocol = transport.transport_server_registry.get()
 
4736
            protocol = transport_server_registry.get()
5122
4737
        host, port = self.get_host_and_port(port)
5123
4738
        url = urlutils.local_path_to_url(directory)
5124
4739
        if not allow_writes:
5125
4740
            url = 'readonly+' + url
5126
 
        t = transport.get_transport(url)
5127
 
        protocol(t, host, port, inet)
 
4741
        transport = get_transport(url)
 
4742
        protocol(transport, host, port, inet)
5128
4743
 
5129
4744
 
5130
4745
class cmd_join(Command):
5131
 
    __doc__ = """Combine a tree into its containing tree.
 
4746
    """Combine a tree into its containing tree.
5132
4747
 
5133
4748
    This command requires the target tree to be in a rich-root format.
5134
4749
 
5136
4751
    not part of it.  (Such trees can be produced by "bzr split", but also by
5137
4752
    running "bzr branch" with the target inside a tree.)
5138
4753
 
5139
 
    The result is a combined tree, with the subtree no longer an independent
 
4754
    The result is a combined tree, with the subtree no longer an independant
5140
4755
    part.  This is marked as a merge of the subtree into the containing tree,
5141
4756
    and all history is preserved.
5142
4757
    """
5174
4789
 
5175
4790
 
5176
4791
class cmd_split(Command):
5177
 
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
4792
    """Split a subdirectory of a tree into a separate tree.
5178
4793
 
5179
4794
    This command will produce a target tree in a format that supports
5180
4795
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
5200
4815
 
5201
4816
 
5202
4817
class cmd_merge_directive(Command):
5203
 
    __doc__ = """Generate a merge directive for auto-merge tools.
 
4818
    """Generate a merge directive for auto-merge tools.
5204
4819
 
5205
4820
    A directive requests a merge to be performed, and also provides all the
5206
4821
    information necessary to do so.  This means it must either include a
5223
4838
    _see_also = ['send']
5224
4839
 
5225
4840
    takes_options = [
5226
 
        'directory',
5227
4841
        RegistryOption.from_kwargs('patch-type',
5228
4842
            'The type of patch to include in the directive.',
5229
4843
            title='Patch type',
5242
4856
    encoding_type = 'exact'
5243
4857
 
5244
4858
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5245
 
            sign=False, revision=None, mail_to=None, message=None,
5246
 
            directory=u'.'):
 
4859
            sign=False, revision=None, mail_to=None, message=None):
5247
4860
        from bzrlib.revision import ensure_null, NULL_REVISION
5248
4861
        include_patch, include_bundle = {
5249
4862
            'plain': (False, False),
5250
4863
            'diff': (True, False),
5251
4864
            'bundle': (True, True),
5252
4865
            }[patch_type]
5253
 
        branch = Branch.open(directory)
 
4866
        branch = Branch.open('.')
5254
4867
        stored_submit_branch = branch.get_submit_branch()
5255
4868
        if submit_branch is None:
5256
4869
            submit_branch = stored_submit_branch
5301
4914
 
5302
4915
 
5303
4916
class cmd_send(Command):
5304
 
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
4917
    """Mail or create a merge-directive for submitting changes.
5305
4918
 
5306
4919
    A merge directive provides many things needed for requesting merges:
5307
4920
 
5313
4926
      directly from the merge directive, without retrieving data from a
5314
4927
      branch.
5315
4928
 
5316
 
    `bzr send` creates a compact data set that, when applied using bzr
5317
 
    merge, has the same effect as merging from the source branch.  
5318
 
    
5319
 
    By default the merge directive is self-contained and can be applied to any
5320
 
    branch containing submit_branch in its ancestory without needing access to
5321
 
    the source branch.
5322
 
    
5323
 
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
5324
 
    revisions, but only a structured request to merge from the
5325
 
    public_location.  In that case the public_branch is needed and it must be
5326
 
    up-to-date and accessible to the recipient.  The public_branch is always
5327
 
    included if known, so that people can check it later.
5328
 
 
5329
 
    The submit branch defaults to the parent of the source branch, but can be
5330
 
    overridden.  Both submit branch and public branch will be remembered in
5331
 
    branch.conf the first time they are used for a particular branch.  The
5332
 
    source branch defaults to that containing the working directory, but can
5333
 
    be changed using --from.
5334
 
 
5335
 
    Both the submit branch and the public branch follow the usual behavior with
5336
 
    respect to --remember: If there is no default location set, the first send
5337
 
    will set it (use --no-remember to avoid settting it). After that, you can
5338
 
    omit the location to use the default.  To change the default, use
5339
 
    --remember. The value will only be saved if the location can be accessed.
5340
 
 
5341
 
    In order to calculate those changes, bzr must analyse the submit branch.
5342
 
    Therefore it is most efficient for the submit branch to be a local mirror.
5343
 
    If a public location is known for the submit_branch, that location is used
5344
 
    in the merge directive.
5345
 
 
5346
 
    The default behaviour is to send the merge directive by mail, unless -o is
5347
 
    given, in which case it is sent to a file.
 
4929
    If --no-bundle is specified, then public_branch is needed (and must be
 
4930
    up-to-date), so that the receiver can perform the merge using the
 
4931
    public_branch.  The public_branch is always included if known, so that
 
4932
    people can check it later.
 
4933
 
 
4934
    The submit branch defaults to the parent, but can be overridden.  Both
 
4935
    submit branch and public branch will be remembered if supplied.
 
4936
 
 
4937
    If a public_branch is known for the submit_branch, that public submit
 
4938
    branch is used in the merge instructions.  This means that a local mirror
 
4939
    can be used as your actual submit branch, once you have set public_branch
 
4940
    for that mirror.
5348
4941
 
5349
4942
    Mail is sent using your preferred mail program.  This should be transparent
5350
 
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
4943
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
5351
4944
    If the preferred client can't be found (or used), your editor will be used.
5352
4945
 
5353
4946
    To use a specific mail program, set the mail_client configuration option.
5354
4947
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
5355
 
    specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5356
 
    Mail.app), "mutt", and "thunderbird"; generic options are "default",
5357
 
    "editor", "emacsclient", "mapi", and "xdg-email".  Plugins may also add
5358
 
    supported clients.
 
4948
    specific clients are "claws", "evolution", "kmail", "mutt", and
 
4949
    "thunderbird"; generic options are "default", "editor", "emacsclient",
 
4950
    "mapi", and "xdg-email".  Plugins may also add supported clients.
5359
4951
 
5360
4952
    If mail is being sent, a to address is required.  This can be supplied
5361
4953
    either on the commandline, by setting the submit_to configuration
5370
4962
 
5371
4963
    The merge directives created by bzr send may be applied using bzr merge or
5372
4964
    bzr pull by specifying a file containing a merge directive as the location.
5373
 
 
5374
 
    bzr send makes extensive use of public locations to map local locations into
5375
 
    URLs that can be used by other people.  See `bzr help configuration` to
5376
 
    set them, and use `bzr info` to display them.
5377
4965
    """
5378
4966
 
5379
4967
    encoding_type = 'exact'
5395
4983
               short_name='f',
5396
4984
               type=unicode),
5397
4985
        Option('output', short_name='o',
5398
 
               help='Write merge directive to this file or directory; '
 
4986
               help='Write merge directive to this file; '
5399
4987
                    'use - for stdout.',
5400
4988
               type=unicode),
5401
4989
        Option('strict',
5412
5000
        ]
5413
5001
 
5414
5002
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5415
 
            no_patch=False, revision=None, remember=None, output=None,
 
5003
            no_patch=False, revision=None, remember=False, output=None,
5416
5004
            format=None, mail_to=None, message=None, body=None,
5417
5005
            strict=None, **kwargs):
5418
5006
        from bzrlib.send import send
5424
5012
 
5425
5013
 
5426
5014
class cmd_bundle_revisions(cmd_send):
5427
 
    __doc__ = """Create a merge-directive for submitting changes.
 
5015
    """Create a merge-directive for submitting changes.
5428
5016
 
5429
5017
    A merge directive provides many things needed for requesting merges:
5430
5018
 
5497
5085
 
5498
5086
 
5499
5087
class cmd_tag(Command):
5500
 
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5088
    """Create, remove or modify a tag naming a revision.
5501
5089
 
5502
5090
    Tags give human-meaningful names to revisions.  Commands that take a -r
5503
5091
    (--revision) option can be given -rtag:X, where X is any previously
5511
5099
 
5512
5100
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
5513
5101
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5514
 
 
5515
 
    If no tag name is specified it will be determined through the 
5516
 
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
5517
 
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
5518
 
    details.
5519
5102
    """
5520
5103
 
5521
5104
    _see_also = ['commit', 'tags']
5522
 
    takes_args = ['tag_name?']
 
5105
    takes_args = ['tag_name']
5523
5106
    takes_options = [
5524
5107
        Option('delete',
5525
5108
            help='Delete this tag rather than placing it.',
5526
5109
            ),
5527
 
        custom_help('directory',
5528
 
            help='Branch in which to place the tag.'),
 
5110
        Option('directory',
 
5111
            help='Branch in which to place the tag.',
 
5112
            short_name='d',
 
5113
            type=unicode,
 
5114
            ),
5529
5115
        Option('force',
5530
5116
            help='Replace existing tags.',
5531
5117
            ),
5532
5118
        'revision',
5533
5119
        ]
5534
5120
 
5535
 
    def run(self, tag_name=None,
 
5121
    def run(self, tag_name,
5536
5122
            delete=None,
5537
5123
            directory='.',
5538
5124
            force=None,
5539
5125
            revision=None,
5540
5126
            ):
5541
5127
        branch, relpath = Branch.open_containing(directory)
5542
 
        self.add_cleanup(branch.lock_write().unlock)
5543
 
        if delete:
5544
 
            if tag_name is None:
5545
 
                raise errors.BzrCommandError("No tag specified to delete.")
5546
 
            branch.tags.delete_tag(tag_name)
5547
 
            note('Deleted tag %s.' % tag_name)
5548
 
        else:
5549
 
            if revision:
5550
 
                if len(revision) != 1:
5551
 
                    raise errors.BzrCommandError(
5552
 
                        "Tags can only be placed on a single revision, "
5553
 
                        "not on a range")
5554
 
                revision_id = revision[0].as_revision_id(branch)
 
5128
        branch.lock_write()
 
5129
        try:
 
5130
            if delete:
 
5131
                branch.tags.delete_tag(tag_name)
 
5132
                self.outf.write('Deleted tag %s.\n' % tag_name)
5555
5133
            else:
5556
 
                revision_id = branch.last_revision()
5557
 
            if tag_name is None:
5558
 
                tag_name = branch.automatic_tag_name(revision_id)
5559
 
                if tag_name is None:
5560
 
                    raise errors.BzrCommandError(
5561
 
                        "Please specify a tag name.")
5562
 
            if (not force) and branch.tags.has_tag(tag_name):
5563
 
                raise errors.TagAlreadyExists(tag_name)
5564
 
            branch.tags.set_tag(tag_name, revision_id)
5565
 
            note('Created tag %s.' % tag_name)
 
5134
                if revision:
 
5135
                    if len(revision) != 1:
 
5136
                        raise errors.BzrCommandError(
 
5137
                            "Tags can only be placed on a single revision, "
 
5138
                            "not on a range")
 
5139
                    revision_id = revision[0].as_revision_id(branch)
 
5140
                else:
 
5141
                    revision_id = branch.last_revision()
 
5142
                if (not force) and branch.tags.has_tag(tag_name):
 
5143
                    raise errors.TagAlreadyExists(tag_name)
 
5144
                branch.tags.set_tag(tag_name, revision_id)
 
5145
                self.outf.write('Created tag %s.\n' % tag_name)
 
5146
        finally:
 
5147
            branch.unlock()
5566
5148
 
5567
5149
 
5568
5150
class cmd_tags(Command):
5569
 
    __doc__ = """List tags.
 
5151
    """List tags.
5570
5152
 
5571
5153
    This command shows a table of tag names and the revisions they reference.
5572
5154
    """
5573
5155
 
5574
5156
    _see_also = ['tag']
5575
5157
    takes_options = [
5576
 
        custom_help('directory',
5577
 
            help='Branch whose tags should be displayed.'),
5578
 
        RegistryOption('sort',
 
5158
        Option('directory',
 
5159
            help='Branch whose tags should be displayed.',
 
5160
            short_name='d',
 
5161
            type=unicode,
 
5162
            ),
 
5163
        RegistryOption.from_kwargs('sort',
5579
5164
            'Sort tags by different criteria.', title='Sorting',
5580
 
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
 
5165
            alpha='Sort tags lexicographically (default).',
 
5166
            time='Sort tags chronologically.',
5581
5167
            ),
5582
5168
        'show-ids',
5583
5169
        'revision',
5584
5170
    ]
5585
5171
 
5586
5172
    @display_command
5587
 
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
5588
 
        from bzrlib.tag import tag_sort_methods
 
5173
    def run(self,
 
5174
            directory='.',
 
5175
            sort='alpha',
 
5176
            show_ids=False,
 
5177
            revision=None,
 
5178
            ):
5589
5179
        branch, relpath = Branch.open_containing(directory)
5590
5180
 
5591
5181
        tags = branch.tags.get_tag_dict().items()
5592
5182
        if not tags:
5593
5183
            return
5594
5184
 
5595
 
        self.add_cleanup(branch.lock_read().unlock)
5596
 
        if revision:
5597
 
            graph = branch.repository.get_graph()
5598
 
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
5599
 
            revid1, revid2 = rev1.rev_id, rev2.rev_id
5600
 
            # only show revisions between revid1 and revid2 (inclusive)
5601
 
            tags = [(tag, revid) for tag, revid in tags if
5602
 
                graph.is_between(revid, revid1, revid2)]
5603
 
        if sort is None:
5604
 
            sort = tag_sort_methods.get()
5605
 
        sort(branch, tags)
5606
 
        if not show_ids:
5607
 
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5608
 
            for index, (tag, revid) in enumerate(tags):
5609
 
                try:
5610
 
                    revno = branch.revision_id_to_dotted_revno(revid)
5611
 
                    if isinstance(revno, tuple):
5612
 
                        revno = '.'.join(map(str, revno))
5613
 
                except (errors.NoSuchRevision, errors.GhostRevisionsHaveNoRevno):
5614
 
                    # Bad tag data/merges can lead to tagged revisions
5615
 
                    # which are not in this branch. Fail gracefully ...
5616
 
                    revno = '?'
5617
 
                tags[index] = (tag, revno)
5618
 
        self.cleanup_now()
 
5185
        branch.lock_read()
 
5186
        try:
 
5187
            if revision:
 
5188
                graph = branch.repository.get_graph()
 
5189
                rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5190
                revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5191
                # only show revisions between revid1 and revid2 (inclusive)
 
5192
                tags = [(tag, revid) for tag, revid in tags if
 
5193
                    graph.is_between(revid, revid1, revid2)]
 
5194
            if sort == 'alpha':
 
5195
                tags.sort()
 
5196
            elif sort == 'time':
 
5197
                timestamps = {}
 
5198
                for tag, revid in tags:
 
5199
                    try:
 
5200
                        revobj = branch.repository.get_revision(revid)
 
5201
                    except errors.NoSuchRevision:
 
5202
                        timestamp = sys.maxint # place them at the end
 
5203
                    else:
 
5204
                        timestamp = revobj.timestamp
 
5205
                    timestamps[revid] = timestamp
 
5206
                tags.sort(key=lambda x: timestamps[x[1]])
 
5207
            if not show_ids:
 
5208
                # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
5209
                for index, (tag, revid) in enumerate(tags):
 
5210
                    try:
 
5211
                        revno = branch.revision_id_to_dotted_revno(revid)
 
5212
                        if isinstance(revno, tuple):
 
5213
                            revno = '.'.join(map(str, revno))
 
5214
                    except errors.NoSuchRevision:
 
5215
                        # Bad tag data/merges can lead to tagged revisions
 
5216
                        # which are not in this branch. Fail gracefully ...
 
5217
                        revno = '?'
 
5218
                    tags[index] = (tag, revno)
 
5219
        finally:
 
5220
            branch.unlock()
5619
5221
        for tag, revspec in tags:
5620
5222
            self.outf.write('%-20s %s\n' % (tag, revspec))
5621
5223
 
5622
5224
 
5623
5225
class cmd_reconfigure(Command):
5624
 
    __doc__ = """Reconfigure the type of a bzr directory.
 
5226
    """Reconfigure the type of a bzr directory.
5625
5227
 
5626
5228
    A target configuration must be specified.
5627
5229
 
5674
5276
            unstacked=None):
5675
5277
        directory = bzrdir.BzrDir.open(location)
5676
5278
        if stacked_on and unstacked:
5677
 
            raise errors.BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5279
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5678
5280
        elif stacked_on is not None:
5679
5281
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5680
5282
        elif unstacked:
5712
5314
 
5713
5315
 
5714
5316
class cmd_switch(Command):
5715
 
    __doc__ = """Set the branch of a checkout and update.
 
5317
    """Set the branch of a checkout and update.
5716
5318
 
5717
5319
    For lightweight checkouts, this changes the branch being referenced.
5718
5320
    For heavyweight checkouts, this checks that there are no local commits
5730
5332
    /path/to/newbranch.
5731
5333
 
5732
5334
    Bound branches use the nickname of its master branch unless it is set
5733
 
    locally, in which case switching will update the local nickname to be
 
5335
    locally, in which case switching will update the the local nickname to be
5734
5336
    that of the master.
5735
5337
    """
5736
5338
 
5737
 
    takes_args = ['to_location?']
5738
 
    takes_options = ['directory',
5739
 
                     Option('force',
 
5339
    takes_args = ['to_location']
 
5340
    takes_options = [Option('force',
5740
5341
                        help='Switch even if local commits will be lost.'),
5741
 
                     'revision',
5742
5342
                     Option('create-branch', short_name='b',
5743
5343
                        help='Create the target branch from this one before'
5744
5344
                             ' switching to it.'),
5745
 
                    ]
 
5345
                     ]
5746
5346
 
5747
 
    def run(self, to_location=None, force=False, create_branch=False,
5748
 
            revision=None, directory=u'.'):
 
5347
    def run(self, to_location, force=False, create_branch=False):
5749
5348
        from bzrlib import switch
5750
 
        tree_location = directory
5751
 
        revision = _get_one_revision('switch', revision)
 
5349
        tree_location = '.'
5752
5350
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5753
 
        if to_location is None:
5754
 
            if revision is None:
5755
 
                raise errors.BzrCommandError('You must supply either a'
5756
 
                                             ' revision or a location')
5757
 
            to_location = tree_location
5758
5351
        try:
5759
5352
            branch = control_dir.open_branch()
5760
5353
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5765
5358
            if branch is None:
5766
5359
                raise errors.BzrCommandError('cannot create branch without'
5767
5360
                                             ' source branch')
5768
 
            to_location = directory_service.directories.dereference(
5769
 
                              to_location)
5770
5361
            if '/' not in to_location and '\\' not in to_location:
5771
5362
                # This path is meant to be relative to the existing branch
5772
5363
                this_url = self._get_branch_location(control_dir)
5774
5365
            to_branch = branch.bzrdir.sprout(to_location,
5775
5366
                                 possible_transports=[branch.bzrdir.root_transport],
5776
5367
                                 source_branch=branch).open_branch()
 
5368
            # try:
 
5369
            #     from_branch = control_dir.open_branch()
 
5370
            # except errors.NotBranchError:
 
5371
            #     raise BzrCommandError('Cannot create a branch from this'
 
5372
            #         ' location when we cannot open this branch')
 
5373
            # from_branch.bzrdir.sprout(
 
5374
            pass
5777
5375
        else:
5778
5376
            try:
5779
5377
                to_branch = Branch.open(to_location)
5781
5379
                this_url = self._get_branch_location(control_dir)
5782
5380
                to_branch = Branch.open(
5783
5381
                    urlutils.join(this_url, '..', to_location))
5784
 
        if revision is not None:
5785
 
            revision = revision.as_revision_id(to_branch)
5786
 
        switch.switch(control_dir, to_branch, force, revision_id=revision)
 
5382
        switch.switch(control_dir, to_branch, force)
5787
5383
        if had_explicit_nick:
5788
5384
            branch = control_dir.open_branch() #get the new branch!
5789
5385
            branch.nick = to_branch.nick
5809
5405
 
5810
5406
 
5811
5407
class cmd_view(Command):
5812
 
    __doc__ = """Manage filtered views.
 
5408
    """Manage filtered views.
5813
5409
 
5814
5410
    Views provide a mask over the tree so that users can focus on
5815
5411
    a subset of a tree when doing their work. After creating a view,
5895
5491
            name=None,
5896
5492
            switch=None,
5897
5493
            ):
5898
 
        tree, file_list = WorkingTree.open_containing_paths(file_list,
5899
 
            apply_view=False)
 
5494
        tree, file_list = tree_files(file_list, apply_view=False)
5900
5495
        current_view, view_dict = tree.views.get_view_info()
5901
5496
        if name is None:
5902
5497
            name = current_view
5964
5559
 
5965
5560
 
5966
5561
class cmd_hooks(Command):
5967
 
    __doc__ = """Show hooks."""
 
5562
    """Show hooks."""
5968
5563
 
5969
5564
    hidden = True
5970
5565
 
5983
5578
                    self.outf.write("    <no hooks installed>\n")
5984
5579
 
5985
5580
 
5986
 
class cmd_remove_branch(Command):
5987
 
    __doc__ = """Remove a branch.
5988
 
 
5989
 
    This will remove the branch from the specified location but 
5990
 
    will keep any working tree or repository in place.
5991
 
 
5992
 
    :Examples:
5993
 
 
5994
 
      Remove the branch at repo/trunk::
5995
 
 
5996
 
        bzr remove-branch repo/trunk
5997
 
 
5998
 
    """
5999
 
 
6000
 
    takes_args = ["location?"]
6001
 
 
6002
 
    aliases = ["rmbranch"]
6003
 
 
6004
 
    def run(self, location=None):
6005
 
        if location is None:
6006
 
            location = "."
6007
 
        branch = Branch.open_containing(location)[0]
6008
 
        branch.bzrdir.destroy_branch()
6009
 
 
6010
 
 
6011
5581
class cmd_shelve(Command):
6012
 
    __doc__ = """Temporarily set aside some changes from the current tree.
 
5582
    """Temporarily set aside some changes from the current tree.
6013
5583
 
6014
5584
    Shelve allows you to temporarily put changes you've made "on the shelf",
6015
5585
    ie. out of the way, until a later time when you can bring them back from
6031
5601
 
6032
5602
    You can put multiple items on the shelf, and by default, 'unshelve' will
6033
5603
    restore the most recently shelved changes.
6034
 
 
6035
 
    For complicated changes, it is possible to edit the changes in a separate
6036
 
    editor program to decide what the file remaining in the working copy
6037
 
    should look like.  To do this, add the configuration option
6038
 
 
6039
 
        change_editor = PROGRAM @new_path @old_path
6040
 
 
6041
 
    where @new_path is replaced with the path of the new version of the 
6042
 
    file and @old_path is replaced with the path of the old version of 
6043
 
    the file.  The PROGRAM should save the new file with the desired 
6044
 
    contents of the file in the working tree.
6045
 
        
6046
5604
    """
6047
5605
 
6048
5606
    takes_args = ['file*']
6049
5607
 
6050
5608
    takes_options = [
6051
 
        'directory',
6052
5609
        'revision',
6053
5610
        Option('all', help='Shelve all changes.'),
6054
5611
        'message',
6060
5617
        Option('destroy',
6061
5618
               help='Destroy removed changes instead of shelving them.'),
6062
5619
    ]
6063
 
    _see_also = ['unshelve', 'configuration']
 
5620
    _see_also = ['unshelve']
6064
5621
 
6065
5622
    def run(self, revision=None, all=False, file_list=None, message=None,
6066
 
            writer=None, list=False, destroy=False, directory=None):
 
5623
            writer=None, list=False, destroy=False):
6067
5624
        if list:
6068
 
            return self.run_for_list(directory=directory)
 
5625
            return self.run_for_list()
6069
5626
        from bzrlib.shelf_ui import Shelver
6070
5627
        if writer is None:
6071
5628
            writer = bzrlib.option.diff_writer_registry.get()
6072
5629
        try:
6073
 
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6074
 
                file_list, message, destroy=destroy, directory=directory)
6075
 
            try:
6076
 
                shelver.run()
6077
 
            finally:
6078
 
                shelver.finalize()
 
5630
            Shelver.from_args(writer(sys.stdout), revision, all, file_list,
 
5631
                              message, destroy=destroy).run()
6079
5632
        except errors.UserAbort:
6080
5633
            return 0
6081
5634
 
6082
 
    def run_for_list(self, directory=None):
6083
 
        if directory is None:
6084
 
            directory = u'.'
6085
 
        tree = WorkingTree.open_containing(directory)[0]
6086
 
        self.add_cleanup(tree.lock_read().unlock)
6087
 
        manager = tree.get_shelf_manager()
6088
 
        shelves = manager.active_shelves()
6089
 
        if len(shelves) == 0:
6090
 
            note('No shelved changes.')
6091
 
            return 0
6092
 
        for shelf_id in reversed(shelves):
6093
 
            message = manager.get_metadata(shelf_id).get('message')
6094
 
            if message is None:
6095
 
                message = '<no message>'
6096
 
            self.outf.write('%3d: %s\n' % (shelf_id, message))
6097
 
        return 1
 
5635
    def run_for_list(self):
 
5636
        tree = WorkingTree.open_containing('.')[0]
 
5637
        tree.lock_read()
 
5638
        try:
 
5639
            manager = tree.get_shelf_manager()
 
5640
            shelves = manager.active_shelves()
 
5641
            if len(shelves) == 0:
 
5642
                note('No shelved changes.')
 
5643
                return 0
 
5644
            for shelf_id in reversed(shelves):
 
5645
                message = manager.get_metadata(shelf_id).get('message')
 
5646
                if message is None:
 
5647
                    message = '<no message>'
 
5648
                self.outf.write('%3d: %s\n' % (shelf_id, message))
 
5649
            return 1
 
5650
        finally:
 
5651
            tree.unlock()
6098
5652
 
6099
5653
 
6100
5654
class cmd_unshelve(Command):
6101
 
    __doc__ = """Restore shelved changes.
 
5655
    """Restore shelved changes.
6102
5656
 
6103
5657
    By default, the most recently shelved changes are restored. However if you
6104
5658
    specify a shelf by id those changes will be restored instead.  This works
6107
5661
 
6108
5662
    takes_args = ['shelf_id?']
6109
5663
    takes_options = [
6110
 
        'directory',
6111
5664
        RegistryOption.from_kwargs(
6112
5665
            'action', help="The action to perform.",
6113
5666
            enum_switch=False, value_switches=True,
6114
5667
            apply="Apply changes and remove from the shelf.",
6115
5668
            dry_run="Show changes, but do not apply or remove them.",
6116
 
            preview="Instead of unshelving the changes, show the diff that "
6117
 
                    "would result from unshelving.",
6118
 
            delete_only="Delete changes without applying them.",
6119
 
            keep="Apply changes but don't delete them.",
 
5669
            delete_only="Delete changes without applying them."
6120
5670
        )
6121
5671
    ]
6122
5672
    _see_also = ['shelve']
6123
5673
 
6124
 
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
5674
    def run(self, shelf_id=None, action='apply'):
6125
5675
        from bzrlib.shelf_ui import Unshelver
6126
 
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
6127
 
        try:
6128
 
            unshelver.run()
6129
 
        finally:
6130
 
            unshelver.tree.unlock()
 
5676
        Unshelver.from_args(shelf_id, action).run()
6131
5677
 
6132
5678
 
6133
5679
class cmd_clean_tree(Command):
6134
 
    __doc__ = """Remove unwanted files from working tree.
 
5680
    """Remove unwanted files from working tree.
6135
5681
 
6136
5682
    By default, only unknown files, not ignored files, are deleted.  Versioned
6137
5683
    files are never deleted.
6145
5691
 
6146
5692
    To check what clean-tree will do, use --dry-run.
6147
5693
    """
6148
 
    takes_options = ['directory',
6149
 
                     Option('ignored', help='Delete all ignored files.'),
6150
 
                     Option('detritus', help='Delete conflict files, merge and revert'
 
5694
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5695
                     Option('detritus', help='Delete conflict files, merge'
6151
5696
                            ' backups, and failed selftest dirs.'),
6152
5697
                     Option('unknown',
6153
5698
                            help='Delete files unknown to bzr (default).'),
6155
5700
                            ' deleting them.'),
6156
5701
                     Option('force', help='Do not prompt before deleting.')]
6157
5702
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6158
 
            force=False, directory=u'.'):
 
5703
            force=False):
6159
5704
        from bzrlib.clean_tree import clean_tree
6160
5705
        if not (unknown or ignored or detritus):
6161
5706
            unknown = True
6162
5707
        if dry_run:
6163
5708
            force = True
6164
 
        clean_tree(directory, unknown=unknown, ignored=ignored,
6165
 
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5709
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5710
                   dry_run=dry_run, no_prompt=force)
6166
5711
 
6167
5712
 
6168
5713
class cmd_reference(Command):
6169
 
    __doc__ = """list, view and set branch locations for nested trees.
 
5714
    """list, view and set branch locations for nested trees.
6170
5715
 
6171
5716
    If no arguments are provided, lists the branch locations for nested trees.
6172
5717
    If one argument is provided, display the branch location for that tree.
6212
5757
            self.outf.write('%s %s\n' % (path, location))
6213
5758
 
6214
5759
 
6215
 
class cmd_export_pot(Command):
6216
 
    __doc__ = """Export command helps and error messages in po format."""
6217
 
 
6218
 
    hidden = True
6219
 
 
6220
 
    def run(self):
6221
 
        from bzrlib.export_pot import export_pot
6222
 
        export_pot(self.outf)
6223
 
 
6224
 
 
6225
 
def _register_lazy_builtins():
6226
 
    # register lazy builtins from other modules; called at startup and should
6227
 
    # be only called once.
6228
 
    for (name, aliases, module_name) in [
6229
 
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6230
 
        ('cmd_config', [], 'bzrlib.config'),
6231
 
        ('cmd_dpush', [], 'bzrlib.foreign'),
6232
 
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6233
 
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6234
 
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6235
 
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6236
 
        ('cmd_verify_signatures', [],
6237
 
                                        'bzrlib.commit_signature_commands'),
6238
 
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6239
 
        ]:
6240
 
        builtin_command_registry.register_lazy(name, aliases, module_name)
 
5760
# these get imported and then picked up by the scan for cmd_*
 
5761
# TODO: Some more consistent way to split command definitions across files;
 
5762
# we do need to load at least some information about them to know of
 
5763
# aliases.  ideally we would avoid loading the implementation until the
 
5764
# details were needed.
 
5765
from bzrlib.cmd_version_info import cmd_version_info
 
5766
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
5767
from bzrlib.bundle.commands import (
 
5768
    cmd_bundle_info,
 
5769
    )
 
5770
from bzrlib.foreign import cmd_dpush
 
5771
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
5772
from bzrlib.weave_commands import cmd_versionedfile_list, \
 
5773
        cmd_weave_plan_merge, cmd_weave_merge_text