~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: John Arbash Meinel
  • Date: 2010-01-05 04:30:07 UTC
  • mfrom: (4932 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4934.
  • Revision ID: john@arbash-meinel.com-20100105043007-ehgbldqd3q0gtyws
Merge bzr.dev, resolve conflicts.

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
32
33
    bzrdir,
33
34
    directory_service,
34
35
    delta,
35
 
    config as _mod_config,
 
36
    config,
36
37
    errors,
37
38
    globbing,
38
39
    hooks,
44
45
    rename_map,
45
46
    revision as _mod_revision,
46
47
    static_tuple,
 
48
    symbol_versioning,
47
49
    timestamp,
48
50
    transport,
49
51
    ui,
50
52
    urlutils,
51
53
    views,
52
 
    gpg,
53
54
    )
54
55
from bzrlib.branch import Branch
55
56
from bzrlib.conflicts import ConflictList
56
 
from bzrlib.transport import memory
57
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
58
58
from bzrlib.smtp_connection import SMTPConnection
59
59
from bzrlib.workingtree import WorkingTree
60
 
from bzrlib.i18n import gettext, ngettext
61
60
""")
62
61
 
63
 
from bzrlib.commands import (
64
 
    Command,
65
 
    builtin_command_registry,
66
 
    display_command,
67
 
    )
 
62
from bzrlib.commands import Command, display_command
68
63
from bzrlib.option import (
69
64
    ListOption,
70
65
    Option,
73
68
    _parse_revision_str,
74
69
    )
75
70
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
76
 
from bzrlib import (
77
 
    symbol_versioning,
78
 
    )
79
 
 
80
 
 
81
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
 
71
 
 
72
 
82
73
def tree_files(file_list, default_branch=u'.', canonicalize=True,
83
74
    apply_view=True):
84
 
    return internal_tree_files(file_list, default_branch, canonicalize,
85
 
        apply_view)
 
75
    try:
 
76
        return internal_tree_files(file_list, default_branch, canonicalize,
 
77
            apply_view)
 
78
    except errors.FileInWrongBranch, e:
 
79
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
 
80
                                     (e.path, file_list[0]))
86
81
 
87
82
 
88
83
def tree_files_for_add(file_list):
113
108
            if view_files:
114
109
                file_list = view_files
115
110
                view_str = views.view_display_str(view_files)
116
 
                note(gettext("Ignoring files outside view. View is %s") % view_str)
 
111
                note("Ignoring files outside view. View is %s" % view_str)
117
112
    return tree, file_list
118
113
 
119
114
 
121
116
    if revisions is None:
122
117
        return None
123
118
    if len(revisions) != 1:
124
 
        raise errors.BzrCommandError(gettext(
125
 
            'bzr %s --revision takes exactly one revision identifier') % (
 
119
        raise errors.BzrCommandError(
 
120
            'bzr %s --revision takes exactly one revision identifier' % (
126
121
                command_name,))
127
122
    return revisions[0]
128
123
 
152
147
 
153
148
# XXX: Bad function name; should possibly also be a class method of
154
149
# WorkingTree rather than a function.
155
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
156
150
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
157
151
    apply_view=True):
158
152
    """Convert command-line paths to a WorkingTree and relative paths.
159
153
 
160
 
    Deprecated: use WorkingTree.open_containing_paths instead.
161
 
 
162
154
    This is typically used for command-line processors that take one or
163
155
    more filenames, and infer the workingtree that contains them.
164
156
 
174
166
 
175
167
    :return: workingtree, [relative_paths]
176
168
    """
177
 
    return WorkingTree.open_containing_paths(
178
 
        file_list, default_directory='.',
179
 
        canonicalize=True,
180
 
        apply_view=True)
 
169
    if file_list is None or len(file_list) == 0:
 
170
        tree = WorkingTree.open_containing(default_branch)[0]
 
171
        if tree.supports_views() and apply_view:
 
172
            view_files = tree.views.lookup_view()
 
173
            if view_files:
 
174
                file_list = view_files
 
175
                view_str = views.view_display_str(view_files)
 
176
                note("Ignoring files outside view. View is %s" % view_str)
 
177
        return tree, file_list
 
178
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
179
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
180
        apply_view=apply_view)
 
181
 
 
182
 
 
183
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
 
184
    """Convert file_list into a list of relpaths in tree.
 
185
 
 
186
    :param tree: A tree to operate on.
 
187
    :param file_list: A list of user provided paths or None.
 
188
    :param apply_view: if True and a view is set, apply it or check that
 
189
        specified files are within it
 
190
    :return: A list of relative paths.
 
191
    :raises errors.PathNotChild: When a provided path is in a different tree
 
192
        than tree.
 
193
    """
 
194
    if file_list is None:
 
195
        return None
 
196
    if tree.supports_views() and apply_view:
 
197
        view_files = tree.views.lookup_view()
 
198
    else:
 
199
        view_files = []
 
200
    new_list = []
 
201
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
 
202
    # doesn't - fix that up here before we enter the loop.
 
203
    if canonicalize:
 
204
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
 
205
    else:
 
206
        fixer = tree.relpath
 
207
    for filename in file_list:
 
208
        try:
 
209
            relpath = fixer(osutils.dereference_path(filename))
 
210
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
211
                raise errors.FileOutsideView(filename, view_files)
 
212
            new_list.append(relpath)
 
213
        except errors.PathNotChild:
 
214
            raise errors.FileInWrongBranch(tree.branch, filename)
 
215
    return new_list
181
216
 
182
217
 
183
218
def _get_view_info_for_change_reporter(tree):
192
227
    return view_info
193
228
 
194
229
 
195
 
def _open_directory_or_containing_tree_or_branch(filename, directory):
196
 
    """Open the tree or branch containing the specified file, unless
197
 
    the --directory option is used to specify a different branch."""
198
 
    if directory is not None:
199
 
        return (None, Branch.open(directory), filename)
200
 
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
201
 
 
202
 
 
203
230
# TODO: Make sure no commands unconditionally use the working directory as a
204
231
# branch.  If a filename argument is used, the first of them should be used to
205
232
# specify the branch.  (Perhaps this can be factored out into some kind of
207
234
# opens the branch?)
208
235
 
209
236
class cmd_status(Command):
210
 
    __doc__ = """Display status summary.
 
237
    """Display status summary.
211
238
 
212
239
    This reports on versioned and unknown files, reporting them
213
240
    grouped by state.  Possible states are:
233
260
    unknown
234
261
        Not versioned and not matching an ignore pattern.
235
262
 
236
 
    Additionally for directories, symlinks and files with a changed
237
 
    executable bit, Bazaar indicates their type using a trailing
238
 
    character: '/', '@' or '*' respectively. These decorations can be
239
 
    disabled using the '--no-classify' option.
 
263
    Additionally for directories, symlinks and files with an executable
 
264
    bit, Bazaar indicates their type using a trailing character: '/', '@'
 
265
    or '*' respectively.
240
266
 
241
267
    To see ignored files use 'bzr ignored'.  For details on the
242
268
    changes to file texts, use 'bzr diff'.
255
281
    To skip the display of pending merge information altogether, use
256
282
    the no-pending option or specify a file/directory.
257
283
 
258
 
    To compare the working directory to a specific revision, pass a
259
 
    single revision to the revision argument.
260
 
 
261
 
    To see which files have changed in a specific revision, or between
262
 
    two revisions, pass a revision range to the revision argument.
263
 
    This will produce the same results as calling 'bzr diff --summarize'.
 
284
    If a revision argument is given, the status is calculated against
 
285
    that revision, or between two revisions if two are provided.
264
286
    """
265
287
 
266
288
    # TODO: --no-recurse, --recurse options
273
295
                            short_name='V'),
274
296
                     Option('no-pending', help='Don\'t show pending merges.',
275
297
                           ),
276
 
                     Option('no-classify',
277
 
                            help='Do not mark object type using indicator.',
278
 
                           ),
279
298
                     ]
280
299
    aliases = ['st', 'stat']
281
300
 
284
303
 
285
304
    @display_command
286
305
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
287
 
            versioned=False, no_pending=False, verbose=False,
288
 
            no_classify=False):
 
306
            versioned=False, no_pending=False, verbose=False):
289
307
        from bzrlib.status import show_tree_status
290
308
 
291
309
        if revision and len(revision) > 2:
292
 
            raise errors.BzrCommandError(gettext('bzr status --revision takes exactly'
293
 
                                         ' one or two revision specifiers'))
 
310
            raise errors.BzrCommandError('bzr status --revision takes exactly'
 
311
                                         ' one or two revision specifiers')
294
312
 
295
 
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
313
        tree, relfile_list = tree_files(file_list)
296
314
        # Avoid asking for specific files when that is not needed.
297
315
        if relfile_list == ['']:
298
316
            relfile_list = None
305
323
        show_tree_status(tree, show_ids=show_ids,
306
324
                         specific_files=relfile_list, revision=revision,
307
325
                         to_file=self.outf, short=short, versioned=versioned,
308
 
                         show_pending=(not no_pending), verbose=verbose,
309
 
                         classify=not no_classify)
 
326
                         show_pending=(not no_pending), verbose=verbose)
310
327
 
311
328
 
312
329
class cmd_cat_revision(Command):
313
 
    __doc__ = """Write out metadata for a revision.
 
330
    """Write out metadata for a revision.
314
331
 
315
332
    The revision to print can either be specified by a specific
316
333
    revision identifier, or you can use --revision.
318
335
 
319
336
    hidden = True
320
337
    takes_args = ['revision_id?']
321
 
    takes_options = ['directory', 'revision']
 
338
    takes_options = ['revision']
322
339
    # cat-revision is more for frontends so should be exact
323
340
    encoding = 'strict'
324
341
 
325
 
    def print_revision(self, revisions, revid):
326
 
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
327
 
        record = stream.next()
328
 
        if record.storage_kind == 'absent':
329
 
            raise errors.NoSuchRevision(revisions, revid)
330
 
        revtext = record.get_bytes_as('fulltext')
331
 
        self.outf.write(revtext.decode('utf-8'))
332
 
 
333
342
    @display_command
334
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
343
    def run(self, revision_id=None, revision=None):
335
344
        if revision_id is not None and revision is not None:
336
 
            raise errors.BzrCommandError(gettext('You can only supply one of'
337
 
                                         ' revision_id or --revision'))
 
345
            raise errors.BzrCommandError('You can only supply one of'
 
346
                                         ' revision_id or --revision')
338
347
        if revision_id is None and revision is None:
339
 
            raise errors.BzrCommandError(gettext('You must supply either'
340
 
                                         ' --revision or a revision_id'))
341
 
 
342
 
        b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
343
 
 
344
 
        revisions = b.repository.revisions
345
 
        if revisions is None:
346
 
            raise errors.BzrCommandError(gettext('Repository %r does not support '
347
 
                'access to raw revision texts'))
348
 
 
349
 
        b.repository.lock_read()
350
 
        try:
351
 
            # TODO: jam 20060112 should cat-revision always output utf-8?
352
 
            if revision_id is not None:
353
 
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
354
 
                try:
355
 
                    self.print_revision(revisions, revision_id)
356
 
                except errors.NoSuchRevision:
357
 
                    msg = gettext("The repository {0} contains no revision {1}.").format(
358
 
                        b.repository.base, revision_id)
359
 
                    raise errors.BzrCommandError(msg)
360
 
            elif revision is not None:
361
 
                for rev in revision:
362
 
                    if rev is None:
363
 
                        raise errors.BzrCommandError(
364
 
                            gettext('You cannot specify a NULL revision.'))
365
 
                    rev_id = rev.as_revision_id(b)
366
 
                    self.print_revision(revisions, rev_id)
367
 
        finally:
368
 
            b.repository.unlock()
369
 
        
 
348
            raise errors.BzrCommandError('You must supply either'
 
349
                                         ' --revision or a revision_id')
 
350
        b = WorkingTree.open_containing(u'.')[0].branch
 
351
 
 
352
        # TODO: jam 20060112 should cat-revision always output utf-8?
 
353
        if revision_id is not None:
 
354
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
 
355
            try:
 
356
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
357
            except errors.NoSuchRevision:
 
358
                msg = "The repository %s contains no revision %s." % (b.repository.base,
 
359
                    revision_id)
 
360
                raise errors.BzrCommandError(msg)
 
361
        elif revision is not None:
 
362
            for rev in revision:
 
363
                if rev is None:
 
364
                    raise errors.BzrCommandError('You cannot specify a NULL'
 
365
                                                 ' revision.')
 
366
                rev_id = rev.as_revision_id(b)
 
367
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
 
368
 
370
369
 
371
370
class cmd_dump_btree(Command):
372
 
    __doc__ = """Dump the contents of a btree index file to stdout.
 
371
    """Dump the contents of a btree index file to stdout.
373
372
 
374
373
    PATH is a btree index file, it can be any URL. This includes things like
375
374
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
423
422
                self.outf.write(page_bytes[:header_end])
424
423
                page_bytes = data
425
424
            self.outf.write('\nPage %d\n' % (page_idx,))
426
 
            if len(page_bytes) == 0:
427
 
                self.outf.write('(empty)\n');
428
 
            else:
429
 
                decomp_bytes = zlib.decompress(page_bytes)
430
 
                self.outf.write(decomp_bytes)
431
 
                self.outf.write('\n')
 
425
            decomp_bytes = zlib.decompress(page_bytes)
 
426
            self.outf.write(decomp_bytes)
 
427
            self.outf.write('\n')
432
428
 
433
429
    def _dump_entries(self, trans, basename):
434
430
        try:
442
438
        for node in bt.iter_all_entries():
443
439
            # Node is made up of:
444
440
            # (index, key, value, [references])
445
 
            try:
446
 
                refs = node[3]
447
 
            except IndexError:
448
 
                refs_as_tuples = None
449
 
            else:
450
 
                refs_as_tuples = static_tuple.as_tuples(refs)
 
441
            refs_as_tuples = static_tuple.as_tuples(node[3])
451
442
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
452
443
            self.outf.write('%s\n' % (as_tuple,))
453
444
 
454
445
 
455
446
class cmd_remove_tree(Command):
456
 
    __doc__ = """Remove the working tree from a given branch/checkout.
 
447
    """Remove the working tree from a given branch/checkout.
457
448
 
458
449
    Since a lightweight checkout is little more than a working tree
459
450
    this will refuse to run against one.
461
452
    To re-create the working tree, use "bzr checkout".
462
453
    """
463
454
    _see_also = ['checkout', 'working-trees']
464
 
    takes_args = ['location*']
 
455
    takes_args = ['location?']
465
456
    takes_options = [
466
457
        Option('force',
467
458
               help='Remove the working tree even if it has '
468
 
                    'uncommitted or shelved changes.'),
 
459
                    'uncommitted changes.'),
469
460
        ]
470
461
 
471
 
    def run(self, location_list, force=False):
472
 
        if not location_list:
473
 
            location_list=['.']
474
 
 
475
 
        for location in location_list:
476
 
            d = bzrdir.BzrDir.open(location)
477
 
            
478
 
            try:
479
 
                working = d.open_workingtree()
480
 
            except errors.NoWorkingTree:
481
 
                raise errors.BzrCommandError(gettext("No working tree to remove"))
482
 
            except errors.NotLocalUrl:
483
 
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
484
 
                                             " of a remote path"))
485
 
            if not force:
486
 
                if (working.has_changes()):
487
 
                    raise errors.UncommittedChanges(working)
488
 
                if working.get_shelf_manager().last_shelf() is not None:
489
 
                    raise errors.ShelvedChanges(working)
490
 
 
491
 
            if working.user_url != working.branch.user_url:
492
 
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
493
 
                                             " from a lightweight checkout"))
494
 
 
495
 
            d.destroy_workingtree()
496
 
 
497
 
 
498
 
class cmd_repair_workingtree(Command):
499
 
    __doc__ = """Reset the working tree state file.
500
 
 
501
 
    This is not meant to be used normally, but more as a way to recover from
502
 
    filesystem corruption, etc. This rebuilds the working inventory back to a
503
 
    'known good' state. Any new modifications (adding a file, renaming, etc)
504
 
    will be lost, though modified files will still be detected as such.
505
 
 
506
 
    Most users will want something more like "bzr revert" or "bzr update"
507
 
    unless the state file has become corrupted.
508
 
 
509
 
    By default this attempts to recover the current state by looking at the
510
 
    headers of the state file. If the state file is too corrupted to even do
511
 
    that, you can supply --revision to force the state of the tree.
512
 
    """
513
 
 
514
 
    takes_options = ['revision', 'directory',
515
 
        Option('force',
516
 
               help='Reset the tree even if it doesn\'t appear to be'
517
 
                    ' corrupted.'),
518
 
    ]
519
 
    hidden = True
520
 
 
521
 
    def run(self, revision=None, directory='.', force=False):
522
 
        tree, _ = WorkingTree.open_containing(directory)
523
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
462
    def run(self, location='.', force=False):
 
463
        d = bzrdir.BzrDir.open(location)
 
464
 
 
465
        try:
 
466
            working = d.open_workingtree()
 
467
        except errors.NoWorkingTree:
 
468
            raise errors.BzrCommandError("No working tree to remove")
 
469
        except errors.NotLocalUrl:
 
470
            raise errors.BzrCommandError("You cannot remove the working tree"
 
471
                                         " of a remote path")
524
472
        if not force:
525
 
            try:
526
 
                tree.check_state()
527
 
            except errors.BzrError:
528
 
                pass # There seems to be a real error here, so we'll reset
529
 
            else:
530
 
                # Refuse
531
 
                raise errors.BzrCommandError(gettext(
532
 
                    'The tree does not appear to be corrupt. You probably'
533
 
                    ' want "bzr revert" instead. Use "--force" if you are'
534
 
                    ' sure you want to reset the working tree.'))
535
 
        if revision is None:
536
 
            revision_ids = None
537
 
        else:
538
 
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
539
 
        try:
540
 
            tree.reset_state(revision_ids)
541
 
        except errors.BzrError, e:
542
 
            if revision_ids is None:
543
 
                extra = (gettext(', the header appears corrupt, try passing -r -1'
544
 
                         ' to set the state to the last commit'))
545
 
            else:
546
 
                extra = ''
547
 
            raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
 
473
            if (working.has_changes()):
 
474
                raise errors.UncommittedChanges(working)
 
475
 
 
476
        working_path = working.bzrdir.root_transport.base
 
477
        branch_path = working.branch.bzrdir.root_transport.base
 
478
        if working_path != branch_path:
 
479
            raise errors.BzrCommandError("You cannot remove the working tree"
 
480
                                         " from a lightweight checkout")
 
481
 
 
482
        d.destroy_workingtree()
548
483
 
549
484
 
550
485
class cmd_revno(Command):
551
 
    __doc__ = """Show current revision number.
 
486
    """Show current revision number.
552
487
 
553
488
    This is equal to the number of revisions on this branch.
554
489
    """
564
499
        if tree:
565
500
            try:
566
501
                wt = WorkingTree.open_containing(location)[0]
567
 
                self.add_cleanup(wt.lock_read().unlock)
 
502
                wt.lock_read()
568
503
            except (errors.NoWorkingTree, errors.NotLocalUrl):
569
504
                raise errors.NoWorkingTree(location)
570
 
            revid = wt.last_revision()
571
505
            try:
572
 
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
573
 
            except errors.NoSuchRevision:
574
 
                revno_t = ('???',)
575
 
            revno = ".".join(str(n) for n in revno_t)
 
506
                revid = wt.last_revision()
 
507
                try:
 
508
                    revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
509
                except errors.NoSuchRevision:
 
510
                    revno_t = ('???',)
 
511
                revno = ".".join(str(n) for n in revno_t)
 
512
            finally:
 
513
                wt.unlock()
576
514
        else:
577
515
            b = Branch.open_containing(location)[0]
578
 
            self.add_cleanup(b.lock_read().unlock)
579
 
            revno = b.revno()
580
 
        self.cleanup_now()
 
516
            b.lock_read()
 
517
            try:
 
518
                revno = b.revno()
 
519
            finally:
 
520
                b.unlock()
 
521
 
581
522
        self.outf.write(str(revno) + '\n')
582
523
 
583
524
 
584
525
class cmd_revision_info(Command):
585
 
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
526
    """Show revision number and revision id for a given revision identifier.
586
527
    """
587
528
    hidden = True
588
529
    takes_args = ['revision_info*']
589
530
    takes_options = [
590
531
        'revision',
591
 
        custom_help('directory',
 
532
        Option('directory',
592
533
            help='Branch to examine, '
593
 
                 'rather than the one containing the working directory.'),
 
534
                 'rather than the one containing the working directory.',
 
535
            short_name='d',
 
536
            type=unicode,
 
537
            ),
594
538
        Option('tree', help='Show revno of working tree'),
595
539
        ]
596
540
 
601
545
        try:
602
546
            wt = WorkingTree.open_containing(directory)[0]
603
547
            b = wt.branch
604
 
            self.add_cleanup(wt.lock_read().unlock)
 
548
            wt.lock_read()
605
549
        except (errors.NoWorkingTree, errors.NotLocalUrl):
606
550
            wt = None
607
551
            b = Branch.open_containing(directory)[0]
608
 
            self.add_cleanup(b.lock_read().unlock)
609
 
        revision_ids = []
610
 
        if revision is not None:
611
 
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
612
 
        if revision_info_list is not None:
613
 
            for rev_str in revision_info_list:
614
 
                rev_spec = RevisionSpec.from_string(rev_str)
615
 
                revision_ids.append(rev_spec.as_revision_id(b))
616
 
        # No arguments supplied, default to the last revision
617
 
        if len(revision_ids) == 0:
618
 
            if tree:
619
 
                if wt is None:
620
 
                    raise errors.NoWorkingTree(directory)
621
 
                revision_ids.append(wt.last_revision())
 
552
            b.lock_read()
 
553
        try:
 
554
            revision_ids = []
 
555
            if revision is not None:
 
556
                revision_ids.extend(rev.as_revision_id(b) for rev in revision)
 
557
            if revision_info_list is not None:
 
558
                for rev_str in revision_info_list:
 
559
                    rev_spec = RevisionSpec.from_string(rev_str)
 
560
                    revision_ids.append(rev_spec.as_revision_id(b))
 
561
            # No arguments supplied, default to the last revision
 
562
            if len(revision_ids) == 0:
 
563
                if tree:
 
564
                    if wt is None:
 
565
                        raise errors.NoWorkingTree(directory)
 
566
                    revision_ids.append(wt.last_revision())
 
567
                else:
 
568
                    revision_ids.append(b.last_revision())
 
569
 
 
570
            revinfos = []
 
571
            maxlen = 0
 
572
            for revision_id in revision_ids:
 
573
                try:
 
574
                    dotted_revno = b.revision_id_to_dotted_revno(revision_id)
 
575
                    revno = '.'.join(str(i) for i in dotted_revno)
 
576
                except errors.NoSuchRevision:
 
577
                    revno = '???'
 
578
                maxlen = max(maxlen, len(revno))
 
579
                revinfos.append([revno, revision_id])
 
580
        finally:
 
581
            if wt is None:
 
582
                b.unlock()
622
583
            else:
623
 
                revision_ids.append(b.last_revision())
624
 
 
625
 
        revinfos = []
626
 
        maxlen = 0
627
 
        for revision_id in revision_ids:
628
 
            try:
629
 
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
630
 
                revno = '.'.join(str(i) for i in dotted_revno)
631
 
            except errors.NoSuchRevision:
632
 
                revno = '???'
633
 
            maxlen = max(maxlen, len(revno))
634
 
            revinfos.append([revno, revision_id])
635
 
 
636
 
        self.cleanup_now()
 
584
                wt.unlock()
 
585
 
637
586
        for ri in revinfos:
638
587
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
639
588
 
640
589
 
641
590
class cmd_add(Command):
642
 
    __doc__ = """Add specified files or directories.
 
591
    """Add specified files or directories.
643
592
 
644
593
    In non-recursive mode, all the named items are added, regardless
645
594
    of whether they were previously ignored.  A warning is given if
653
602
    are added.  This search proceeds recursively into versioned
654
603
    directories.  If no names are given '.' is assumed.
655
604
 
656
 
    A warning will be printed when nested trees are encountered,
657
 
    unless they are explicitly ignored.
658
 
 
659
605
    Therefore simply saying 'bzr add' will version all files that
660
606
    are currently unknown.
661
607
 
677
623
    
678
624
    Any files matching patterns in the ignore list will not be added
679
625
    unless they are explicitly mentioned.
680
 
    
681
 
    In recursive mode, files larger than the configuration option 
682
 
    add.maximum_file_size will be skipped. Named items are never skipped due
683
 
    to file size.
684
626
    """
685
627
    takes_args = ['file*']
686
628
    takes_options = [
713
655
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
714
656
                          to_file=self.outf, should_print=(not is_quiet()))
715
657
        else:
716
 
            action = bzrlib.add.AddWithSkipLargeAction(to_file=self.outf,
 
658
            action = bzrlib.add.AddAction(to_file=self.outf,
717
659
                should_print=(not is_quiet()))
718
660
 
719
661
        if base_tree:
720
 
            self.add_cleanup(base_tree.lock_read().unlock)
721
 
        tree, file_list = tree_files_for_add(file_list)
722
 
        added, ignored = tree.smart_add(file_list, not
723
 
            no_recurse, action=action, save=not dry_run)
724
 
        self.cleanup_now()
 
662
            base_tree.lock_read()
 
663
        try:
 
664
            tree, file_list = tree_files_for_add(file_list)
 
665
            added, ignored = tree.smart_add(file_list, not
 
666
                no_recurse, action=action, save=not dry_run)
 
667
        finally:
 
668
            if base_tree is not None:
 
669
                base_tree.unlock()
725
670
        if len(ignored) > 0:
726
671
            if verbose:
727
672
                for glob in sorted(ignored.keys()):
728
673
                    for path in ignored[glob]:
729
 
                        self.outf.write(
730
 
                         gettext("ignored {0} matching \"{1}\"\n").format(
731
 
                         path, glob))
 
674
                        self.outf.write("ignored %s matching \"%s\"\n"
 
675
                                        % (path, glob))
732
676
 
733
677
 
734
678
class cmd_mkdir(Command):
735
 
    __doc__ = """Create a new versioned directory.
 
679
    """Create a new versioned directory.
736
680
 
737
681
    This is equivalent to creating the directory and then adding it.
738
682
    """
742
686
 
743
687
    def run(self, dir_list):
744
688
        for d in dir_list:
 
689
            os.mkdir(d)
745
690
            wt, dd = WorkingTree.open_containing(d)
746
 
            base = os.path.dirname(dd)
747
 
            id = wt.path2id(base)
748
 
            if id != None:
749
 
                os.mkdir(d)
750
 
                wt.add([dd])
751
 
                self.outf.write(gettext('added %s\n') % d)
752
 
            else:
753
 
                raise errors.NotVersionedError(path=base)
 
691
            wt.add([dd])
 
692
            self.outf.write('added %s\n' % d)
754
693
 
755
694
 
756
695
class cmd_relpath(Command):
757
 
    __doc__ = """Show path of a file relative to root"""
 
696
    """Show path of a file relative to root"""
758
697
 
759
698
    takes_args = ['filename']
760
699
    hidden = True
769
708
 
770
709
 
771
710
class cmd_inventory(Command):
772
 
    __doc__ = """Show inventory of the current working copy or a revision.
 
711
    """Show inventory of the current working copy or a revision.
773
712
 
774
713
    It is possible to limit the output to a particular entry
775
714
    type using the --kind option.  For example: --kind file.
792
731
    @display_command
793
732
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
794
733
        if kind and kind not in ['file', 'directory', 'symlink']:
795
 
            raise errors.BzrCommandError(gettext('invalid kind %r specified') % (kind,))
 
734
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
796
735
 
797
736
        revision = _get_one_revision('inventory', revision)
798
 
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
799
 
        self.add_cleanup(work_tree.lock_read().unlock)
800
 
        if revision is not None:
801
 
            tree = revision.as_tree(work_tree.branch)
802
 
 
803
 
            extra_trees = [work_tree]
804
 
            self.add_cleanup(tree.lock_read().unlock)
805
 
        else:
806
 
            tree = work_tree
807
 
            extra_trees = []
808
 
 
809
 
        if file_list is not None:
810
 
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
811
 
                                      require_versioned=True)
812
 
            # find_ids_across_trees may include some paths that don't
813
 
            # exist in 'tree'.
814
 
            entries = sorted(
815
 
                (tree.id2path(file_id), tree.inventory[file_id])
816
 
                for file_id in file_ids if tree.has_id(file_id))
817
 
        else:
818
 
            entries = tree.inventory.entries()
819
 
 
820
 
        self.cleanup_now()
 
737
        work_tree, file_list = tree_files(file_list)
 
738
        work_tree.lock_read()
 
739
        try:
 
740
            if revision is not None:
 
741
                tree = revision.as_tree(work_tree.branch)
 
742
 
 
743
                extra_trees = [work_tree]
 
744
                tree.lock_read()
 
745
            else:
 
746
                tree = work_tree
 
747
                extra_trees = []
 
748
 
 
749
            if file_list is not None:
 
750
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
751
                                          require_versioned=True)
 
752
                # find_ids_across_trees may include some paths that don't
 
753
                # exist in 'tree'.
 
754
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
755
                                 for file_id in file_ids if file_id in tree)
 
756
            else:
 
757
                entries = tree.inventory.entries()
 
758
        finally:
 
759
            tree.unlock()
 
760
            if tree is not work_tree:
 
761
                work_tree.unlock()
 
762
 
821
763
        for path, entry in entries:
822
764
            if kind and kind != entry.kind:
823
765
                continue
829
771
 
830
772
 
831
773
class cmd_mv(Command):
832
 
    __doc__ = """Move or rename a file.
 
774
    """Move or rename a file.
833
775
 
834
776
    :Usage:
835
777
        bzr mv OLDNAME NEWNAME
862
804
        if auto:
863
805
            return self.run_auto(names_list, after, dry_run)
864
806
        elif dry_run:
865
 
            raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
 
807
            raise errors.BzrCommandError('--dry-run requires --auto.')
866
808
        if names_list is None:
867
809
            names_list = []
868
810
        if len(names_list) < 2:
869
 
            raise errors.BzrCommandError(gettext("missing file argument"))
870
 
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
871
 
        self.add_cleanup(tree.lock_tree_write().unlock)
872
 
        self._run(tree, names_list, rel_names, after)
 
811
            raise errors.BzrCommandError("missing file argument")
 
812
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
813
        tree.lock_tree_write()
 
814
        try:
 
815
            self._run(tree, names_list, rel_names, after)
 
816
        finally:
 
817
            tree.unlock()
873
818
 
874
819
    def run_auto(self, names_list, after, dry_run):
875
820
        if names_list is not None and len(names_list) > 1:
876
 
            raise errors.BzrCommandError(gettext('Only one path may be specified to'
877
 
                                         ' --auto.'))
 
821
            raise errors.BzrCommandError('Only one path may be specified to'
 
822
                                         ' --auto.')
878
823
        if after:
879
 
            raise errors.BzrCommandError(gettext('--after cannot be specified with'
880
 
                                         ' --auto.'))
881
 
        work_tree, file_list = WorkingTree.open_containing_paths(
882
 
            names_list, default_directory='.')
883
 
        self.add_cleanup(work_tree.lock_tree_write().unlock)
884
 
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
824
            raise errors.BzrCommandError('--after cannot be specified with'
 
825
                                         ' --auto.')
 
826
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
827
        work_tree.lock_tree_write()
 
828
        try:
 
829
            rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
830
        finally:
 
831
            work_tree.unlock()
885
832
 
886
833
    def _run(self, tree, names_list, rel_names, after):
887
834
        into_existing = osutils.isdir(names_list[-1])
913
860
                    self.outf.write("%s => %s\n" % (src, dest))
914
861
        else:
915
862
            if len(names_list) != 2:
916
 
                raise errors.BzrCommandError(gettext('to mv multiple files the'
 
863
                raise errors.BzrCommandError('to mv multiple files the'
917
864
                                             ' destination must be a versioned'
918
 
                                             ' directory'))
 
865
                                             ' directory')
919
866
 
920
867
            # for cicp file-systems: the src references an existing inventory
921
868
            # item:
965
912
 
966
913
 
967
914
class cmd_pull(Command):
968
 
    __doc__ = """Turn this branch into a mirror of another branch.
 
915
    """Turn this branch into a mirror of another branch.
969
916
 
970
917
    By default, this command only works on branches that have not diverged.
971
918
    Branches are considered diverged if the destination branch's most recent 
980
927
    match the remote one, use pull --overwrite. This will work even if the two
981
928
    branches have diverged.
982
929
 
983
 
    If there is no default location set, the first pull will set it (use
984
 
    --no-remember to avoid setting it). After that, you can omit the
985
 
    location to use the default.  To change the default, use --remember. The
986
 
    value will only be saved if the remote location can be accessed.
 
930
    If there is no default location set, the first pull will set it.  After
 
931
    that, you can omit the location to use the default.  To change the
 
932
    default, use --remember. The value will only be saved if the remote
 
933
    location can be accessed.
987
934
 
988
935
    Note: The location can be specified either in the form of a branch,
989
936
    or in the form of a path to a file containing a merge directive generated
994
941
    takes_options = ['remember', 'overwrite', 'revision',
995
942
        custom_help('verbose',
996
943
            help='Show logs of pulled revisions.'),
997
 
        custom_help('directory',
 
944
        Option('directory',
998
945
            help='Branch to pull into, '
999
 
                 'rather than the one containing the working directory.'),
 
946
                 'rather than the one containing the working directory.',
 
947
            short_name='d',
 
948
            type=unicode,
 
949
            ),
1000
950
        Option('local',
1001
951
            help="Perform a local pull in a bound "
1002
952
                 "branch.  Local pulls are not applied to "
1003
953
                 "the master branch."
1004
954
            ),
1005
 
        Option('show-base',
1006
 
            help="Show base revision text in conflicts.")
1007
955
        ]
1008
956
    takes_args = ['location?']
1009
957
    encoding_type = 'replace'
1010
958
 
1011
 
    def run(self, location=None, remember=None, overwrite=False,
 
959
    def run(self, location=None, remember=False, overwrite=False,
1012
960
            revision=None, verbose=False,
1013
 
            directory=None, local=False,
1014
 
            show_base=False):
 
961
            directory=None, local=False):
1015
962
        # FIXME: too much stuff is in the command class
1016
963
        revision_id = None
1017
964
        mergeable = None
1020
967
        try:
1021
968
            tree_to = WorkingTree.open_containing(directory)[0]
1022
969
            branch_to = tree_to.branch
1023
 
            self.add_cleanup(tree_to.lock_write().unlock)
1024
970
        except errors.NoWorkingTree:
1025
971
            tree_to = None
1026
972
            branch_to = Branch.open_containing(directory)[0]
1027
 
            self.add_cleanup(branch_to.lock_write().unlock)
1028
 
 
1029
 
        if tree_to is None and show_base:
1030
 
            raise errors.BzrCommandError(gettext("Need working tree for --show-base."))
1031
 
 
 
973
        
1032
974
        if local and not branch_to.get_bound_location():
1033
975
            raise errors.LocalRequiresBoundBranch()
1034
976
 
1043
985
        stored_loc = branch_to.get_parent()
1044
986
        if location is None:
1045
987
            if stored_loc is None:
1046
 
                raise errors.BzrCommandError(gettext("No pull location known or"
1047
 
                                             " specified."))
 
988
                raise errors.BzrCommandError("No pull location known or"
 
989
                                             " specified.")
1048
990
            else:
1049
991
                display_url = urlutils.unescape_for_display(stored_loc,
1050
992
                        self.outf.encoding)
1051
993
                if not is_quiet():
1052
 
                    self.outf.write(gettext("Using saved parent location: %s\n") % display_url)
 
994
                    self.outf.write("Using saved parent location: %s\n" % display_url)
1053
995
                location = stored_loc
1054
996
 
1055
997
        revision = _get_one_revision('pull', revision)
1056
998
        if mergeable is not None:
1057
999
            if revision is not None:
1058
 
                raise errors.BzrCommandError(gettext(
1059
 
                    'Cannot use -r with merge directives or bundles'))
 
1000
                raise errors.BzrCommandError(
 
1001
                    'Cannot use -r with merge directives or bundles')
1060
1002
            mergeable.install_revisions(branch_to.repository)
1061
1003
            base_revision_id, revision_id, verified = \
1062
1004
                mergeable.get_merge_request(branch_to.repository)
1064
1006
        else:
1065
1007
            branch_from = Branch.open(location,
1066
1008
                possible_transports=possible_transports)
1067
 
            self.add_cleanup(branch_from.lock_read().unlock)
1068
 
            # Remembers if asked explicitly or no previous location is set
1069
 
            if (remember
1070
 
                or (remember is None and branch_to.get_parent() is None)):
 
1009
 
 
1010
            if branch_to.get_parent() is None or remember:
1071
1011
                branch_to.set_parent(branch_from.base)
1072
1012
 
1073
 
        if revision is not None:
1074
 
            revision_id = revision.as_revision_id(branch_from)
1075
 
 
1076
 
        if tree_to is not None:
1077
 
            view_info = _get_view_info_for_change_reporter(tree_to)
1078
 
            change_reporter = delta._ChangeReporter(
1079
 
                unversioned_filter=tree_to.is_ignored,
1080
 
                view_info=view_info)
1081
 
            result = tree_to.pull(
1082
 
                branch_from, overwrite, revision_id, change_reporter,
1083
 
                local=local, show_base=show_base)
1084
 
        else:
1085
 
            result = branch_to.pull(
1086
 
                branch_from, overwrite, revision_id, local=local)
1087
 
 
1088
 
        result.report(self.outf)
1089
 
        if verbose and result.old_revid != result.new_revid:
1090
 
            log.show_branch_change(
1091
 
                branch_to, self.outf, result.old_revno,
1092
 
                result.old_revid)
1093
 
        if getattr(result, 'tag_conflicts', None):
1094
 
            return 1
1095
 
        else:
1096
 
            return 0
 
1013
        if branch_from is not branch_to:
 
1014
            branch_from.lock_read()
 
1015
        try:
 
1016
            if revision is not None:
 
1017
                revision_id = revision.as_revision_id(branch_from)
 
1018
 
 
1019
            branch_to.lock_write()
 
1020
            try:
 
1021
                if tree_to is not None:
 
1022
                    view_info = _get_view_info_for_change_reporter(tree_to)
 
1023
                    change_reporter = delta._ChangeReporter(
 
1024
                        unversioned_filter=tree_to.is_ignored,
 
1025
                        view_info=view_info)
 
1026
                    result = tree_to.pull(
 
1027
                        branch_from, overwrite, revision_id, change_reporter,
 
1028
                        possible_transports=possible_transports, local=local)
 
1029
                else:
 
1030
                    result = branch_to.pull(
 
1031
                        branch_from, overwrite, revision_id, local=local)
 
1032
 
 
1033
                result.report(self.outf)
 
1034
                if verbose and result.old_revid != result.new_revid:
 
1035
                    log.show_branch_change(
 
1036
                        branch_to, self.outf, result.old_revno,
 
1037
                        result.old_revid)
 
1038
            finally:
 
1039
                branch_to.unlock()
 
1040
        finally:
 
1041
            if branch_from is not branch_to:
 
1042
                branch_from.unlock()
1097
1043
 
1098
1044
 
1099
1045
class cmd_push(Command):
1100
 
    __doc__ = """Update a mirror of this branch.
 
1046
    """Update a mirror of this branch.
1101
1047
 
1102
1048
    The target branch will not have its working tree populated because this
1103
1049
    is both expensive, and is not supported on remote file systems.
1116
1062
    do a merge (see bzr help merge) from the other branch, and commit that.
1117
1063
    After that you will be able to do a push without '--overwrite'.
1118
1064
 
1119
 
    If there is no default push location set, the first push will set it (use
1120
 
    --no-remember to avoid setting it).  After that, you can omit the
1121
 
    location to use the default.  To change the default, use --remember. The
1122
 
    value will only be saved if the remote location can be accessed.
 
1065
    If there is no default push location set, the first push will set it.
 
1066
    After that, you can omit the location to use the default.  To change the
 
1067
    default, use --remember. The value will only be saved if the remote
 
1068
    location can be accessed.
1123
1069
    """
1124
1070
 
1125
1071
    _see_also = ['pull', 'update', 'working-trees']
1127
1073
        Option('create-prefix',
1128
1074
               help='Create the path leading up to the branch '
1129
1075
                    'if it does not already exist.'),
1130
 
        custom_help('directory',
 
1076
        Option('directory',
1131
1077
            help='Branch to push from, '
1132
 
                 'rather than the one containing the working directory.'),
 
1078
                 'rather than the one containing the working directory.',
 
1079
            short_name='d',
 
1080
            type=unicode,
 
1081
            ),
1133
1082
        Option('use-existing-dir',
1134
1083
               help='By default push will fail if the target'
1135
1084
                    ' directory exists, but does not already'
1146
1095
        Option('strict',
1147
1096
               help='Refuse to push if there are uncommitted changes in'
1148
1097
               ' the working tree, --no-strict disables the check.'),
1149
 
        Option('no-tree',
1150
 
               help="Don't populate the working tree, even for protocols"
1151
 
               " that support it."),
1152
1098
        ]
1153
1099
    takes_args = ['location?']
1154
1100
    encoding_type = 'replace'
1155
1101
 
1156
 
    def run(self, location=None, remember=None, overwrite=False,
 
1102
    def run(self, location=None, remember=False, overwrite=False,
1157
1103
        create_prefix=False, verbose=False, revision=None,
1158
1104
        use_existing_dir=False, directory=None, stacked_on=None,
1159
 
        stacked=False, strict=None, no_tree=False):
 
1105
        stacked=False, strict=None):
1160
1106
        from bzrlib.push import _show_push_branch
1161
1107
 
1162
1108
        if directory is None:
1164
1110
        # Get the source branch
1165
1111
        (tree, br_from,
1166
1112
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1113
        if strict is None:
 
1114
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
 
1115
        if strict is None: strict = True # default value
1167
1116
        # Get the tip's revision_id
1168
1117
        revision = _get_one_revision('push', revision)
1169
1118
        if revision is not None:
1170
1119
            revision_id = revision.in_history(br_from).rev_id
1171
1120
        else:
1172
1121
            revision_id = None
1173
 
        if tree is not None and revision_id is None:
1174
 
            tree.check_changed_or_out_of_date(
1175
 
                strict, 'push_strict',
1176
 
                more_error='Use --no-strict to force the push.',
1177
 
                more_warning='Uncommitted changes will not be pushed.')
 
1122
        if strict and tree is not None and revision_id is None:
 
1123
            if (tree.has_changes()):
 
1124
                raise errors.UncommittedChanges(
 
1125
                    tree, more='Use --no-strict to force the push.')
 
1126
            if tree.last_revision() != tree.branch.last_revision():
 
1127
                # The tree has lost sync with its branch, there is little
 
1128
                # chance that the user is aware of it but he can still force
 
1129
                # the push with --no-strict
 
1130
                raise errors.OutOfDateTree(
 
1131
                    tree, more='Use --no-strict to force the push.')
 
1132
 
1178
1133
        # Get the stacked_on branch, if any
1179
1134
        if stacked_on is not None:
1180
1135
            stacked_on = urlutils.normalize_url(stacked_on)
1190
1145
                    # error by the feedback given to them. RBC 20080227.
1191
1146
                    stacked_on = parent_url
1192
1147
            if not stacked_on:
1193
 
                raise errors.BzrCommandError(gettext(
1194
 
                    "Could not determine branch to refer to."))
 
1148
                raise errors.BzrCommandError(
 
1149
                    "Could not determine branch to refer to.")
1195
1150
 
1196
1151
        # Get the destination location
1197
1152
        if location is None:
1198
1153
            stored_loc = br_from.get_push_location()
1199
1154
            if stored_loc is None:
1200
 
                raise errors.BzrCommandError(gettext(
1201
 
                    "No push location known or specified."))
 
1155
                raise errors.BzrCommandError(
 
1156
                    "No push location known or specified.")
1202
1157
            else:
1203
1158
                display_url = urlutils.unescape_for_display(stored_loc,
1204
1159
                        self.outf.encoding)
1205
 
                note(gettext("Using saved push location: %s") % display_url)
 
1160
                self.outf.write("Using saved push location: %s\n" % display_url)
1206
1161
                location = stored_loc
1207
1162
 
1208
1163
        _show_push_branch(br_from, revision_id, location, self.outf,
1209
1164
            verbose=verbose, overwrite=overwrite, remember=remember,
1210
1165
            stacked_on=stacked_on, create_prefix=create_prefix,
1211
 
            use_existing_dir=use_existing_dir, no_tree=no_tree)
 
1166
            use_existing_dir=use_existing_dir)
1212
1167
 
1213
1168
 
1214
1169
class cmd_branch(Command):
1215
 
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
1170
    """Create a new branch that is a copy of an existing branch.
1216
1171
 
1217
1172
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1218
1173
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1223
1178
 
1224
1179
    To retrieve the branch as of a particular revision, supply the --revision
1225
1180
    parameter, as in "branch foo/bar -r 5".
1226
 
 
1227
 
    The synonyms 'clone' and 'get' for this command are deprecated.
1228
1181
    """
1229
1182
 
1230
1183
    _see_also = ['checkout']
1231
1184
    takes_args = ['from_location', 'to_location?']
1232
 
    takes_options = ['revision',
1233
 
        Option('hardlink', help='Hard-link working tree files where possible.'),
1234
 
        Option('files-from', type=str,
1235
 
               help="Get file contents from this tree."),
 
1185
    takes_options = ['revision', Option('hardlink',
 
1186
        help='Hard-link working tree files where possible.'),
1236
1187
        Option('no-tree',
1237
1188
            help="Create a branch without a working-tree."),
1238
1189
        Option('switch',
1249
1200
                    ' directory exists, but does not already'
1250
1201
                    ' have a control directory.  This flag will'
1251
1202
                    ' allow branch to proceed.'),
1252
 
        Option('bind',
1253
 
            help="Bind new branch to from location."),
1254
1203
        ]
1255
1204
    aliases = ['get', 'clone']
1256
1205
 
1257
1206
    def run(self, from_location, to_location=None, revision=None,
1258
1207
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1259
 
            use_existing_dir=False, switch=False, bind=False,
1260
 
            files_from=None):
 
1208
            use_existing_dir=False, switch=False):
1261
1209
        from bzrlib import switch as _mod_switch
1262
1210
        from bzrlib.tag import _merge_tags_if_possible
1263
 
        if self.invoked_as in ['get', 'clone']:
1264
 
            ui.ui_factory.show_user_warning(
1265
 
                'deprecated_command',
1266
 
                deprecated_name=self.invoked_as,
1267
 
                recommended_name='branch',
1268
 
                deprecated_in_version='2.4')
1269
1211
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1270
1212
            from_location)
1271
 
        if not (hardlink or files_from):
1272
 
            # accelerator_tree is usually slower because you have to read N
1273
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1274
 
            # explicitly request it
1275
 
            accelerator_tree = None
1276
 
        if files_from is not None and files_from != from_location:
1277
 
            accelerator_tree = WorkingTree.open(files_from)
1278
1213
        revision = _get_one_revision('branch', revision)
1279
 
        self.add_cleanup(br_from.lock_read().unlock)
1280
 
        if revision is not None:
1281
 
            revision_id = revision.as_revision_id(br_from)
1282
 
        else:
1283
 
            # FIXME - wt.last_revision, fallback to branch, fall back to
1284
 
            # None or perhaps NULL_REVISION to mean copy nothing
1285
 
            # RBC 20060209
1286
 
            revision_id = br_from.last_revision()
1287
 
        if to_location is None:
1288
 
            to_location = urlutils.derive_to_location(from_location)
1289
 
        to_transport = transport.get_transport(to_location)
 
1214
        br_from.lock_read()
1290
1215
        try:
1291
 
            to_transport.mkdir('.')
1292
 
        except errors.FileExists:
1293
 
            if not use_existing_dir:
1294
 
                raise errors.BzrCommandError(gettext('Target directory "%s" '
1295
 
                    'already exists.') % to_location)
 
1216
            if revision is not None:
 
1217
                revision_id = revision.as_revision_id(br_from)
1296
1218
            else:
1297
 
                try:
1298
 
                    bzrdir.BzrDir.open_from_transport(to_transport)
1299
 
                except errors.NotBranchError:
1300
 
                    pass
1301
 
                else:
1302
 
                    raise errors.AlreadyBranchError(to_location)
1303
 
        except errors.NoSuchFile:
1304
 
            raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
1305
 
                                         % to_location)
1306
 
        try:
1307
 
            # preserve whatever source format we have.
1308
 
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1309
 
                                        possible_transports=[to_transport],
1310
 
                                        accelerator_tree=accelerator_tree,
1311
 
                                        hardlink=hardlink, stacked=stacked,
1312
 
                                        force_new_repo=standalone,
1313
 
                                        create_tree_if_local=not no_tree,
1314
 
                                        source_branch=br_from)
1315
 
            branch = dir.open_branch()
1316
 
        except errors.NoSuchRevision:
1317
 
            to_transport.delete_tree('.')
1318
 
            msg = gettext("The branch {0} has no revision {1}.").format(
1319
 
                from_location, revision)
1320
 
            raise errors.BzrCommandError(msg)
1321
 
        _merge_tags_if_possible(br_from, branch)
1322
 
        # If the source branch is stacked, the new branch may
1323
 
        # be stacked whether we asked for that explicitly or not.
1324
 
        # We therefore need a try/except here and not just 'if stacked:'
1325
 
        try:
1326
 
            note(gettext('Created new stacked branch referring to %s.') %
1327
 
                branch.get_stacked_on_url())
1328
 
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1329
 
            errors.UnstackableRepositoryFormat), e:
1330
 
            note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
1331
 
        if bind:
1332
 
            # Bind to the parent
1333
 
            parent_branch = Branch.open(from_location)
1334
 
            branch.bind(parent_branch)
1335
 
            note(gettext('New branch bound to %s') % from_location)
1336
 
        if switch:
1337
 
            # Switch to the new branch
1338
 
            wt, _ = WorkingTree.open_containing('.')
1339
 
            _mod_switch.switch(wt.bzrdir, branch)
1340
 
            note(gettext('Switched to branch: %s'),
1341
 
                urlutils.unescape_for_display(branch.base, 'utf-8'))
1342
 
 
1343
 
 
1344
 
class cmd_branches(Command):
1345
 
    __doc__ = """List the branches available at the current location.
1346
 
 
1347
 
    This command will print the names of all the branches at the current
1348
 
    location.
1349
 
    """
1350
 
 
1351
 
    takes_args = ['location?']
1352
 
    takes_options = [
1353
 
                  Option('recursive', short_name='R',
1354
 
                         help='Recursively scan for branches rather than '
1355
 
                              'just looking in the specified location.')]
1356
 
 
1357
 
    def run(self, location=".", recursive=False):
1358
 
        if recursive:
1359
 
            t = transport.get_transport(location)
1360
 
            if not t.listable():
1361
 
                raise errors.BzrCommandError(
1362
 
                    "Can't scan this type of location.")
1363
 
            for b in bzrdir.BzrDir.find_branches(t):
1364
 
                self.outf.write("%s\n" % urlutils.unescape_for_display(
1365
 
                    urlutils.relative_url(t.base, b.base),
1366
 
                    self.outf.encoding).rstrip("/"))
1367
 
        else:
1368
 
            dir = bzrdir.BzrDir.open_containing(location)[0]
1369
 
            for branch in dir.list_branches():
1370
 
                if branch.name is None:
1371
 
                    self.outf.write(gettext(" (default)\n"))
1372
 
                else:
1373
 
                    self.outf.write(" %s\n" % branch.name.encode(
1374
 
                        self.outf.encoding))
 
1219
                # FIXME - wt.last_revision, fallback to branch, fall back to
 
1220
                # None or perhaps NULL_REVISION to mean copy nothing
 
1221
                # RBC 20060209
 
1222
                revision_id = br_from.last_revision()
 
1223
            if to_location is None:
 
1224
                to_location = urlutils.derive_to_location(from_location)
 
1225
            to_transport = transport.get_transport(to_location)
 
1226
            try:
 
1227
                to_transport.mkdir('.')
 
1228
            except errors.FileExists:
 
1229
                if not use_existing_dir:
 
1230
                    raise errors.BzrCommandError('Target directory "%s" '
 
1231
                        'already exists.' % to_location)
 
1232
                else:
 
1233
                    try:
 
1234
                        bzrdir.BzrDir.open_from_transport(to_transport)
 
1235
                    except errors.NotBranchError:
 
1236
                        pass
 
1237
                    else:
 
1238
                        raise errors.AlreadyBranchError(to_location)
 
1239
            except errors.NoSuchFile:
 
1240
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
 
1241
                                             % to_location)
 
1242
            try:
 
1243
                # preserve whatever source format we have.
 
1244
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
1245
                                            possible_transports=[to_transport],
 
1246
                                            accelerator_tree=accelerator_tree,
 
1247
                                            hardlink=hardlink, stacked=stacked,
 
1248
                                            force_new_repo=standalone,
 
1249
                                            create_tree_if_local=not no_tree,
 
1250
                                            source_branch=br_from)
 
1251
                branch = dir.open_branch()
 
1252
            except errors.NoSuchRevision:
 
1253
                to_transport.delete_tree('.')
 
1254
                msg = "The branch %s has no revision %s." % (from_location,
 
1255
                    revision)
 
1256
                raise errors.BzrCommandError(msg)
 
1257
            _merge_tags_if_possible(br_from, branch)
 
1258
            # If the source branch is stacked, the new branch may
 
1259
            # be stacked whether we asked for that explicitly or not.
 
1260
            # We therefore need a try/except here and not just 'if stacked:'
 
1261
            try:
 
1262
                note('Created new stacked branch referring to %s.' %
 
1263
                    branch.get_stacked_on_url())
 
1264
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
1265
                errors.UnstackableRepositoryFormat), e:
 
1266
                note('Branched %d revision(s).' % branch.revno())
 
1267
            if switch:
 
1268
                # Switch to the new branch
 
1269
                wt, _ = WorkingTree.open_containing('.')
 
1270
                _mod_switch.switch(wt.bzrdir, branch)
 
1271
                note('Switched to branch: %s',
 
1272
                    urlutils.unescape_for_display(branch.base, 'utf-8'))
 
1273
        finally:
 
1274
            br_from.unlock()
1375
1275
 
1376
1276
 
1377
1277
class cmd_checkout(Command):
1378
 
    __doc__ = """Create a new checkout of an existing branch.
 
1278
    """Create a new checkout of an existing branch.
1379
1279
 
1380
1280
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1381
1281
    the branch found in '.'. This is useful if you have removed the working tree
1420
1320
            to_location = branch_location
1421
1321
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1422
1322
            branch_location)
1423
 
        if not (hardlink or files_from):
1424
 
            # accelerator_tree is usually slower because you have to read N
1425
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1426
 
            # explicitly request it
1427
 
            accelerator_tree = None
1428
1323
        revision = _get_one_revision('checkout', revision)
1429
 
        if files_from is not None and files_from != branch_location:
 
1324
        if files_from is not None:
1430
1325
            accelerator_tree = WorkingTree.open(files_from)
1431
1326
        if revision is not None:
1432
1327
            revision_id = revision.as_revision_id(source)
1449
1344
 
1450
1345
 
1451
1346
class cmd_renames(Command):
1452
 
    __doc__ = """Show list of renamed files.
 
1347
    """Show list of renamed files.
1453
1348
    """
1454
1349
    # TODO: Option to show renames between two historical versions.
1455
1350
 
1460
1355
    @display_command
1461
1356
    def run(self, dir=u'.'):
1462
1357
        tree = WorkingTree.open_containing(dir)[0]
1463
 
        self.add_cleanup(tree.lock_read().unlock)
1464
 
        new_inv = tree.inventory
1465
 
        old_tree = tree.basis_tree()
1466
 
        self.add_cleanup(old_tree.lock_read().unlock)
1467
 
        old_inv = old_tree.inventory
1468
 
        renames = []
1469
 
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1470
 
        for f, paths, c, v, p, n, k, e in iterator:
1471
 
            if paths[0] == paths[1]:
1472
 
                continue
1473
 
            if None in (paths):
1474
 
                continue
1475
 
            renames.append(paths)
1476
 
        renames.sort()
1477
 
        for old_name, new_name in renames:
1478
 
            self.outf.write("%s => %s\n" % (old_name, new_name))
 
1358
        tree.lock_read()
 
1359
        try:
 
1360
            new_inv = tree.inventory
 
1361
            old_tree = tree.basis_tree()
 
1362
            old_tree.lock_read()
 
1363
            try:
 
1364
                old_inv = old_tree.inventory
 
1365
                renames = []
 
1366
                iterator = tree.iter_changes(old_tree, include_unchanged=True)
 
1367
                for f, paths, c, v, p, n, k, e in iterator:
 
1368
                    if paths[0] == paths[1]:
 
1369
                        continue
 
1370
                    if None in (paths):
 
1371
                        continue
 
1372
                    renames.append(paths)
 
1373
                renames.sort()
 
1374
                for old_name, new_name in renames:
 
1375
                    self.outf.write("%s => %s\n" % (old_name, new_name))
 
1376
            finally:
 
1377
                old_tree.unlock()
 
1378
        finally:
 
1379
            tree.unlock()
1479
1380
 
1480
1381
 
1481
1382
class cmd_update(Command):
1482
 
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1383
    """Update a tree to have the latest code committed to its branch.
1483
1384
 
1484
1385
    This will perform a merge into the working tree, and may generate
1485
1386
    conflicts. If you have any local changes, you will still
1488
1389
    If you want to discard your local changes, you can just do a
1489
1390
    'bzr revert' instead of 'bzr commit' after the update.
1490
1391
 
1491
 
    If you want to restore a file that has been removed locally, use
1492
 
    'bzr revert' instead of 'bzr update'.
1493
 
 
1494
1392
    If the tree's branch is bound to a master branch, it will also update
1495
1393
    the branch from the master.
1496
1394
    """
1497
1395
 
1498
1396
    _see_also = ['pull', 'working-trees', 'status-flags']
1499
1397
    takes_args = ['dir?']
1500
 
    takes_options = ['revision',
1501
 
                     Option('show-base',
1502
 
                            help="Show base revision text in conflicts."),
1503
 
                     ]
 
1398
    takes_options = ['revision']
1504
1399
    aliases = ['up']
1505
1400
 
1506
 
    def run(self, dir='.', revision=None, show_base=None):
 
1401
    def run(self, dir='.', revision=None):
1507
1402
        if revision is not None and len(revision) != 1:
1508
 
            raise errors.BzrCommandError(gettext(
1509
 
                        "bzr update --revision takes exactly one revision"))
 
1403
            raise errors.BzrCommandError(
 
1404
                        "bzr update --revision takes exactly one revision")
1510
1405
        tree = WorkingTree.open_containing(dir)[0]
1511
1406
        branch = tree.branch
1512
1407
        possible_transports = []
1513
1408
        master = branch.get_master_branch(
1514
1409
            possible_transports=possible_transports)
1515
1410
        if master is not None:
 
1411
            tree.lock_write()
1516
1412
            branch_location = master.base
1517
 
            tree.lock_write()
1518
1413
        else:
 
1414
            tree.lock_tree_write()
1519
1415
            branch_location = tree.branch.base
1520
 
            tree.lock_tree_write()
1521
 
        self.add_cleanup(tree.unlock)
1522
1416
        # get rid of the final '/' and be ready for display
1523
 
        branch_location = urlutils.unescape_for_display(
1524
 
            branch_location.rstrip('/'),
1525
 
            self.outf.encoding)
1526
 
        existing_pending_merges = tree.get_parent_ids()[1:]
1527
 
        if master is None:
1528
 
            old_tip = None
1529
 
        else:
1530
 
            # may need to fetch data into a heavyweight checkout
1531
 
            # XXX: this may take some time, maybe we should display a
1532
 
            # message
1533
 
            old_tip = branch.update(possible_transports)
1534
 
        if revision is not None:
1535
 
            revision_id = revision[0].as_revision_id(branch)
1536
 
        else:
1537
 
            revision_id = branch.last_revision()
1538
 
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1539
 
            revno = branch.revision_id_to_dotted_revno(revision_id)
1540
 
            note(gettext("Tree is up to date at revision {0} of branch {1}"
1541
 
                        ).format('.'.join(map(str, revno)), branch_location))
1542
 
            return 0
1543
 
        view_info = _get_view_info_for_change_reporter(tree)
1544
 
        change_reporter = delta._ChangeReporter(
1545
 
            unversioned_filter=tree.is_ignored,
1546
 
            view_info=view_info)
 
1417
        branch_location = urlutils.unescape_for_display(branch_location[:-1],
 
1418
                                                        self.outf.encoding)
1547
1419
        try:
1548
 
            conflicts = tree.update(
1549
 
                change_reporter,
1550
 
                possible_transports=possible_transports,
1551
 
                revision=revision_id,
1552
 
                old_tip=old_tip,
1553
 
                show_base=show_base)
1554
 
        except errors.NoSuchRevision, e:
1555
 
            raise errors.BzrCommandError(gettext(
1556
 
                                  "branch has no revision %s\n"
1557
 
                                  "bzr update --revision only works"
1558
 
                                  " for a revision in the branch history")
1559
 
                                  % (e.revision))
1560
 
        revno = tree.branch.revision_id_to_dotted_revno(
1561
 
            _mod_revision.ensure_null(tree.last_revision()))
1562
 
        note(gettext('Updated to revision {0} of branch {1}').format(
1563
 
             '.'.join(map(str, revno)), branch_location))
1564
 
        parent_ids = tree.get_parent_ids()
1565
 
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1566
 
            note(gettext('Your local commits will now show as pending merges with '
1567
 
                 "'bzr status', and can be committed with 'bzr commit'."))
1568
 
        if conflicts != 0:
1569
 
            return 1
1570
 
        else:
1571
 
            return 0
 
1420
            existing_pending_merges = tree.get_parent_ids()[1:]
 
1421
            if master is None:
 
1422
                old_tip = None
 
1423
            else:
 
1424
                # may need to fetch data into a heavyweight checkout
 
1425
                # XXX: this may take some time, maybe we should display a
 
1426
                # message
 
1427
                old_tip = branch.update(possible_transports)
 
1428
            if revision is not None:
 
1429
                revision_id = revision[0].as_revision_id(branch)
 
1430
            else:
 
1431
                revision_id = branch.last_revision()
 
1432
            if revision_id == _mod_revision.ensure_null(tree.last_revision()):
 
1433
                revno = branch.revision_id_to_revno(revision_id)
 
1434
                note("Tree is up to date at revision %d of branch %s" %
 
1435
                    (revno, branch_location))
 
1436
                return 0
 
1437
            view_info = _get_view_info_for_change_reporter(tree)
 
1438
            change_reporter = delta._ChangeReporter(
 
1439
                unversioned_filter=tree.is_ignored,
 
1440
                view_info=view_info)
 
1441
            try:
 
1442
                conflicts = tree.update(
 
1443
                    change_reporter,
 
1444
                    possible_transports=possible_transports,
 
1445
                    revision=revision_id,
 
1446
                    old_tip=old_tip)
 
1447
            except errors.NoSuchRevision, e:
 
1448
                raise errors.BzrCommandError(
 
1449
                                      "branch has no revision %s\n"
 
1450
                                      "bzr update --revision only works"
 
1451
                                      " for a revision in the branch history"
 
1452
                                      % (e.revision))
 
1453
            revno = tree.branch.revision_id_to_revno(
 
1454
                _mod_revision.ensure_null(tree.last_revision()))
 
1455
            note('Updated to revision %d of branch %s' %
 
1456
                 (revno, branch_location))
 
1457
            if tree.get_parent_ids()[1:] != existing_pending_merges:
 
1458
                note('Your local commits will now show as pending merges with '
 
1459
                     "'bzr status', and can be committed with 'bzr commit'.")
 
1460
            if conflicts != 0:
 
1461
                return 1
 
1462
            else:
 
1463
                return 0
 
1464
        finally:
 
1465
            tree.unlock()
1572
1466
 
1573
1467
 
1574
1468
class cmd_info(Command):
1575
 
    __doc__ = """Show information about a working tree, branch or repository.
 
1469
    """Show information about a working tree, branch or repository.
1576
1470
 
1577
1471
    This command will show all known locations and formats associated to the
1578
1472
    tree, branch or repository.
1616
1510
 
1617
1511
 
1618
1512
class cmd_remove(Command):
1619
 
    __doc__ = """Remove files or directories.
 
1513
    """Remove files or directories.
1620
1514
 
1621
 
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1622
 
    delete them if they can easily be recovered using revert otherwise they
1623
 
    will be backed up (adding an extention of the form .~#~). If no options or
1624
 
    parameters are given Bazaar will scan for files that are being tracked by
1625
 
    Bazaar but missing in your tree and stop tracking them for you.
 
1515
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1516
    them if they can easily be recovered using revert. If no options or
 
1517
    parameters are given bzr will scan for files that are being tracked by bzr
 
1518
    but missing in your tree and stop tracking them for you.
1626
1519
    """
1627
1520
    takes_args = ['file*']
1628
1521
    takes_options = ['verbose',
1630
1523
        RegistryOption.from_kwargs('file-deletion-strategy',
1631
1524
            'The file deletion mode to be used.',
1632
1525
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1633
 
            safe='Backup changed files (default).',
 
1526
            safe='Only delete files if they can be'
 
1527
                 ' safely recovered (default).',
1634
1528
            keep='Delete from bzr but leave the working copy.',
1635
 
            no_backup='Don\'t backup changed files.',
1636
1529
            force='Delete all the specified files, even if they can not be '
1637
 
                'recovered and even if they are non-empty directories. '
1638
 
                '(deprecated, use no-backup)')]
 
1530
                'recovered and even if they are non-empty directories.')]
1639
1531
    aliases = ['rm', 'del']
1640
1532
    encoding_type = 'replace'
1641
1533
 
1642
1534
    def run(self, file_list, verbose=False, new=False,
1643
1535
        file_deletion_strategy='safe'):
1644
 
        if file_deletion_strategy == 'force':
1645
 
            note(gettext("(The --force option is deprecated, rather use --no-backup "
1646
 
                "in future.)"))
1647
 
            file_deletion_strategy = 'no-backup'
1648
 
 
1649
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1536
        tree, file_list = tree_files(file_list)
1650
1537
 
1651
1538
        if file_list is not None:
1652
1539
            file_list = [f for f in file_list]
1653
1540
 
1654
 
        self.add_cleanup(tree.lock_write().unlock)
1655
 
        # Heuristics should probably all move into tree.remove_smart or
1656
 
        # some such?
1657
 
        if new:
1658
 
            added = tree.changes_from(tree.basis_tree(),
1659
 
                specific_files=file_list).added
1660
 
            file_list = sorted([f[0] for f in added], reverse=True)
1661
 
            if len(file_list) == 0:
1662
 
                raise errors.BzrCommandError(gettext('No matching files.'))
1663
 
        elif file_list is None:
1664
 
            # missing files show up in iter_changes(basis) as
1665
 
            # versioned-with-no-kind.
1666
 
            missing = []
1667
 
            for change in tree.iter_changes(tree.basis_tree()):
1668
 
                # Find paths in the working tree that have no kind:
1669
 
                if change[1][1] is not None and change[6][1] is None:
1670
 
                    missing.append(change[1][1])
1671
 
            file_list = sorted(missing, reverse=True)
1672
 
            file_deletion_strategy = 'keep'
1673
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1674
 
            keep_files=file_deletion_strategy=='keep',
1675
 
            force=(file_deletion_strategy=='no-backup'))
 
1541
        tree.lock_write()
 
1542
        try:
 
1543
            # Heuristics should probably all move into tree.remove_smart or
 
1544
            # some such?
 
1545
            if new:
 
1546
                added = tree.changes_from(tree.basis_tree(),
 
1547
                    specific_files=file_list).added
 
1548
                file_list = sorted([f[0] for f in added], reverse=True)
 
1549
                if len(file_list) == 0:
 
1550
                    raise errors.BzrCommandError('No matching files.')
 
1551
            elif file_list is None:
 
1552
                # missing files show up in iter_changes(basis) as
 
1553
                # versioned-with-no-kind.
 
1554
                missing = []
 
1555
                for change in tree.iter_changes(tree.basis_tree()):
 
1556
                    # Find paths in the working tree that have no kind:
 
1557
                    if change[1][1] is not None and change[6][1] is None:
 
1558
                        missing.append(change[1][1])
 
1559
                file_list = sorted(missing, reverse=True)
 
1560
                file_deletion_strategy = 'keep'
 
1561
            tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1562
                keep_files=file_deletion_strategy=='keep',
 
1563
                force=file_deletion_strategy=='force')
 
1564
        finally:
 
1565
            tree.unlock()
1676
1566
 
1677
1567
 
1678
1568
class cmd_file_id(Command):
1679
 
    __doc__ = """Print file_id of a particular file or directory.
 
1569
    """Print file_id of a particular file or directory.
1680
1570
 
1681
1571
    The file_id is assigned when the file is first added and remains the
1682
1572
    same through all revisions where the file exists, even when it is
1698
1588
 
1699
1589
 
1700
1590
class cmd_file_path(Command):
1701
 
    __doc__ = """Print path of file_ids to a file or directory.
 
1591
    """Print path of file_ids to a file or directory.
1702
1592
 
1703
1593
    This prints one line for each directory down to the target,
1704
1594
    starting at the branch root.
1720
1610
 
1721
1611
 
1722
1612
class cmd_reconcile(Command):
1723
 
    __doc__ = """Reconcile bzr metadata in a branch.
 
1613
    """Reconcile bzr metadata in a branch.
1724
1614
 
1725
1615
    This can correct data mismatches that may have been caused by
1726
1616
    previous ghost operations or bzr upgrades. You should only
1740
1630
 
1741
1631
    _see_also = ['check']
1742
1632
    takes_args = ['branch?']
1743
 
    takes_options = [
1744
 
        Option('canonicalize-chks',
1745
 
               help='Make sure CHKs are in canonical form (repairs '
1746
 
                    'bug 522637).',
1747
 
               hidden=True),
1748
 
        ]
1749
1633
 
1750
 
    def run(self, branch=".", canonicalize_chks=False):
 
1634
    def run(self, branch="."):
1751
1635
        from bzrlib.reconcile import reconcile
1752
1636
        dir = bzrdir.BzrDir.open(branch)
1753
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1637
        reconcile(dir)
1754
1638
 
1755
1639
 
1756
1640
class cmd_revision_history(Command):
1757
 
    __doc__ = """Display the list of revision ids on a branch."""
 
1641
    """Display the list of revision ids on a branch."""
1758
1642
 
1759
1643
    _see_also = ['log']
1760
1644
    takes_args = ['location?']
1770
1654
 
1771
1655
 
1772
1656
class cmd_ancestry(Command):
1773
 
    __doc__ = """List all revisions merged into this branch."""
 
1657
    """List all revisions merged into this branch."""
1774
1658
 
1775
1659
    _see_also = ['log', 'revision-history']
1776
1660
    takes_args = ['location?']
1788
1672
            b = wt.branch
1789
1673
            last_revision = wt.last_revision()
1790
1674
 
1791
 
        self.add_cleanup(b.repository.lock_read().unlock)
1792
 
        graph = b.repository.get_graph()
1793
 
        revisions = [revid for revid, parents in
1794
 
            graph.iter_ancestry([last_revision])]
1795
 
        for revision_id in reversed(revisions):
1796
 
            if _mod_revision.is_null(revision_id):
1797
 
                continue
 
1675
        revision_ids = b.repository.get_ancestry(last_revision)
 
1676
        revision_ids.pop(0)
 
1677
        for revision_id in revision_ids:
1798
1678
            self.outf.write(revision_id + '\n')
1799
1679
 
1800
1680
 
1801
1681
class cmd_init(Command):
1802
 
    __doc__ = """Make a directory into a versioned branch.
 
1682
    """Make a directory into a versioned branch.
1803
1683
 
1804
1684
    Use this to create an empty branch, or before importing an
1805
1685
    existing project.
1837
1717
                ),
1838
1718
         Option('append-revisions-only',
1839
1719
                help='Never change revnos or the existing log.'
1840
 
                '  Append revisions to it only.'),
1841
 
         Option('no-tree',
1842
 
                'Create a branch without a working tree.')
 
1720
                '  Append revisions to it only.')
1843
1721
         ]
1844
1722
    def run(self, location=None, format=None, append_revisions_only=False,
1845
 
            create_prefix=False, no_tree=False):
 
1723
            create_prefix=False):
1846
1724
        if format is None:
1847
1725
            format = bzrdir.format_registry.make_bzrdir('default')
1848
1726
        if location is None:
1859
1737
            to_transport.ensure_base()
1860
1738
        except errors.NoSuchFile:
1861
1739
            if not create_prefix:
1862
 
                raise errors.BzrCommandError(gettext("Parent directory of %s"
 
1740
                raise errors.BzrCommandError("Parent directory of %s"
1863
1741
                    " does not exist."
1864
1742
                    "\nYou may supply --create-prefix to create all"
1865
 
                    " leading parent directories.")
 
1743
                    " leading parent directories."
1866
1744
                    % location)
1867
1745
            to_transport.create_prefix()
1868
1746
 
1871
1749
        except errors.NotBranchError:
1872
1750
            # really a NotBzrDir error...
1873
1751
            create_branch = bzrdir.BzrDir.create_branch_convenience
1874
 
            if no_tree:
1875
 
                force_new_tree = False
1876
 
            else:
1877
 
                force_new_tree = None
1878
1752
            branch = create_branch(to_transport.base, format=format,
1879
 
                                   possible_transports=[to_transport],
1880
 
                                   force_new_tree=force_new_tree)
 
1753
                                   possible_transports=[to_transport])
1881
1754
            a_bzrdir = branch.bzrdir
1882
1755
        else:
1883
1756
            from bzrlib.transport.local import LocalTransport
1887
1760
                        raise errors.BranchExistsWithoutWorkingTree(location)
1888
1761
                raise errors.AlreadyBranchError(location)
1889
1762
            branch = a_bzrdir.create_branch()
1890
 
            if not no_tree:
1891
 
                a_bzrdir.create_workingtree()
 
1763
            a_bzrdir.create_workingtree()
1892
1764
        if append_revisions_only:
1893
1765
            try:
1894
1766
                branch.set_append_revisions_only(True)
1895
1767
            except errors.UpgradeRequired:
1896
 
                raise errors.BzrCommandError(gettext('This branch format cannot be set'
1897
 
                    ' to append-revisions-only.  Try --default.'))
 
1768
                raise errors.BzrCommandError('This branch format cannot be set'
 
1769
                    ' to append-revisions-only.  Try --default.')
1898
1770
        if not is_quiet():
1899
1771
            from bzrlib.info import describe_layout, describe_format
1900
1772
            try:
1904
1776
            repository = branch.repository
1905
1777
            layout = describe_layout(repository, branch, tree).lower()
1906
1778
            format = describe_format(a_bzrdir, repository, branch, tree)
1907
 
            self.outf.write(gettext("Created a {0} (format: {1})\n").format(
1908
 
                  layout, format))
 
1779
            self.outf.write("Created a %s (format: %s)\n" % (layout, format))
1909
1780
            if repository.is_shared():
1910
1781
                #XXX: maybe this can be refactored into transport.path_or_url()
1911
1782
                url = repository.bzrdir.root_transport.external_url()
1913
1784
                    url = urlutils.local_path_from_url(url)
1914
1785
                except errors.InvalidURL:
1915
1786
                    pass
1916
 
                self.outf.write(gettext("Using shared repository: %s\n") % url)
 
1787
                self.outf.write("Using shared repository: %s\n" % url)
1917
1788
 
1918
1789
 
1919
1790
class cmd_init_repository(Command):
1920
 
    __doc__ = """Create a shared repository for branches to share storage space.
 
1791
    """Create a shared repository for branches to share storage space.
1921
1792
 
1922
1793
    New branches created under the repository directory will store their
1923
1794
    revisions in the repository, not in the branch directory.  For branches
1977
1848
 
1978
1849
 
1979
1850
class cmd_diff(Command):
1980
 
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1851
    """Show differences in the working tree, between revisions or branches.
1981
1852
 
1982
1853
    If no arguments are given, all changes for the current tree are listed.
1983
1854
    If files are given, only the changes in those files are listed.
1989
1860
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1990
1861
    produces patches suitable for "patch -p1".
1991
1862
 
1992
 
    Note that when using the -r argument with a range of revisions, the
1993
 
    differences are computed between the two specified revisions.  That
1994
 
    is, the command does not show the changes introduced by the first 
1995
 
    revision in the range.  This differs from the interpretation of 
1996
 
    revision ranges used by "bzr log" which includes the first revision
1997
 
    in the range.
1998
 
 
1999
1863
    :Exit values:
2000
1864
        1 - changed
2001
1865
        2 - unrepresentable changes
2019
1883
 
2020
1884
            bzr diff -r1..3 xxx
2021
1885
 
2022
 
        The changes introduced by revision 2 (equivalent to -r1..2)::
2023
 
 
2024
 
            bzr diff -c2
2025
 
 
2026
 
        To see the changes introduced by revision X::
 
1886
        To see the changes introduced in revision X::
2027
1887
        
2028
1888
            bzr diff -cX
2029
1889
 
2033
1893
 
2034
1894
            bzr diff -r<chosen_parent>..X
2035
1895
 
2036
 
        The changes between the current revision and the previous revision
2037
 
        (equivalent to -c-1 and -r-2..-1)
 
1896
        The changes introduced by revision 2 (equivalent to -r1..2)::
2038
1897
 
2039
 
            bzr diff -r-2..
 
1898
            bzr diff -c2
2040
1899
 
2041
1900
        Show just the differences for file NEWS::
2042
1901
 
2057
1916
        Same as 'bzr diff' but prefix paths with old/ and new/::
2058
1917
 
2059
1918
            bzr diff --prefix old/:new/
2060
 
            
2061
 
        Show the differences using a custom diff program with options::
2062
 
        
2063
 
            bzr diff --using /usr/bin/diff --diff-options -wu
2064
1919
    """
2065
1920
    _see_also = ['status']
2066
1921
    takes_args = ['file*']
2085
1940
            help='Use this command to compare files.',
2086
1941
            type=unicode,
2087
1942
            ),
2088
 
        RegistryOption('format',
2089
 
            short_name='F',
2090
 
            help='Diff format to use.',
2091
 
            lazy_registry=('bzrlib.diff', 'format_registry'),
2092
 
            title='Diff format'),
2093
1943
        ]
2094
1944
    aliases = ['di', 'dif']
2095
1945
    encoding_type = 'exact'
2096
1946
 
2097
1947
    @display_command
2098
1948
    def run(self, revision=None, file_list=None, diff_options=None,
2099
 
            prefix=None, old=None, new=None, using=None, format=None):
2100
 
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
2101
 
            show_diff_trees)
 
1949
            prefix=None, old=None, new=None, using=None):
 
1950
        from bzrlib.diff import get_trees_and_branches_to_diff, show_diff_trees
2102
1951
 
2103
1952
        if (prefix is None) or (prefix == '0'):
2104
1953
            # diff -p0 format
2110
1959
        elif ':' in prefix:
2111
1960
            old_label, new_label = prefix.split(":")
2112
1961
        else:
2113
 
            raise errors.BzrCommandError(gettext(
 
1962
            raise errors.BzrCommandError(
2114
1963
                '--prefix expects two values separated by a colon'
2115
 
                ' (eg "old/:new/")'))
 
1964
                ' (eg "old/:new/")')
2116
1965
 
2117
1966
        if revision and len(revision) > 2:
2118
 
            raise errors.BzrCommandError(gettext('bzr diff --revision takes exactly'
2119
 
                                         ' one or two revision specifiers'))
2120
 
 
2121
 
        if using is not None and format is not None:
2122
 
            raise errors.BzrCommandError(gettext(
2123
 
                '{0} and {1} are mutually exclusive').format(
2124
 
                '--using', '--format'))
 
1967
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
 
1968
                                         ' one or two revision specifiers')
2125
1969
 
2126
1970
        (old_tree, new_tree,
2127
1971
         old_branch, new_branch,
2128
 
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
2129
 
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
2130
 
        # GNU diff on Windows uses ANSI encoding for filenames
2131
 
        path_encoding = osutils.get_diff_header_encoding()
 
1972
         specific_files, extra_trees) = get_trees_and_branches_to_diff(
 
1973
            file_list, revision, old, new, apply_view=True)
2132
1974
        return show_diff_trees(old_tree, new_tree, sys.stdout,
2133
1975
                               specific_files=specific_files,
2134
1976
                               external_diff_options=diff_options,
2135
1977
                               old_label=old_label, new_label=new_label,
2136
 
                               extra_trees=extra_trees,
2137
 
                               path_encoding=path_encoding,
2138
 
                               using=using,
2139
 
                               format_cls=format)
 
1978
                               extra_trees=extra_trees, using=using)
2140
1979
 
2141
1980
 
2142
1981
class cmd_deleted(Command):
2143
 
    __doc__ = """List files deleted in the working tree.
 
1982
    """List files deleted in the working tree.
2144
1983
    """
2145
1984
    # TODO: Show files deleted since a previous revision, or
2146
1985
    # between two revisions.
2149
1988
    # level of effort but possibly much less IO.  (Or possibly not,
2150
1989
    # if the directories are very large...)
2151
1990
    _see_also = ['status', 'ls']
2152
 
    takes_options = ['directory', 'show-ids']
 
1991
    takes_options = ['show-ids']
2153
1992
 
2154
1993
    @display_command
2155
 
    def run(self, show_ids=False, directory=u'.'):
2156
 
        tree = WorkingTree.open_containing(directory)[0]
2157
 
        self.add_cleanup(tree.lock_read().unlock)
2158
 
        old = tree.basis_tree()
2159
 
        self.add_cleanup(old.lock_read().unlock)
2160
 
        for path, ie in old.inventory.iter_entries():
2161
 
            if not tree.has_id(ie.file_id):
2162
 
                self.outf.write(path)
2163
 
                if show_ids:
2164
 
                    self.outf.write(' ')
2165
 
                    self.outf.write(ie.file_id)
2166
 
                self.outf.write('\n')
 
1994
    def run(self, show_ids=False):
 
1995
        tree = WorkingTree.open_containing(u'.')[0]
 
1996
        tree.lock_read()
 
1997
        try:
 
1998
            old = tree.basis_tree()
 
1999
            old.lock_read()
 
2000
            try:
 
2001
                for path, ie in old.inventory.iter_entries():
 
2002
                    if not tree.has_id(ie.file_id):
 
2003
                        self.outf.write(path)
 
2004
                        if show_ids:
 
2005
                            self.outf.write(' ')
 
2006
                            self.outf.write(ie.file_id)
 
2007
                        self.outf.write('\n')
 
2008
            finally:
 
2009
                old.unlock()
 
2010
        finally:
 
2011
            tree.unlock()
2167
2012
 
2168
2013
 
2169
2014
class cmd_modified(Command):
2170
 
    __doc__ = """List files modified in working tree.
 
2015
    """List files modified in working tree.
2171
2016
    """
2172
2017
 
2173
2018
    hidden = True
2174
2019
    _see_also = ['status', 'ls']
2175
 
    takes_options = ['directory', 'null']
 
2020
    takes_options = [
 
2021
            Option('null',
 
2022
                   help='Write an ascii NUL (\\0) separator '
 
2023
                   'between files rather than a newline.')
 
2024
            ]
2176
2025
 
2177
2026
    @display_command
2178
 
    def run(self, null=False, directory=u'.'):
2179
 
        tree = WorkingTree.open_containing(directory)[0]
2180
 
        self.add_cleanup(tree.lock_read().unlock)
 
2027
    def run(self, null=False):
 
2028
        tree = WorkingTree.open_containing(u'.')[0]
2181
2029
        td = tree.changes_from(tree.basis_tree())
2182
 
        self.cleanup_now()
2183
2030
        for path, id, kind, text_modified, meta_modified in td.modified:
2184
2031
            if null:
2185
2032
                self.outf.write(path + '\0')
2188
2035
 
2189
2036
 
2190
2037
class cmd_added(Command):
2191
 
    __doc__ = """List files added in working tree.
 
2038
    """List files added in working tree.
2192
2039
    """
2193
2040
 
2194
2041
    hidden = True
2195
2042
    _see_also = ['status', 'ls']
2196
 
    takes_options = ['directory', 'null']
 
2043
    takes_options = [
 
2044
            Option('null',
 
2045
                   help='Write an ascii NUL (\\0) separator '
 
2046
                   'between files rather than a newline.')
 
2047
            ]
2197
2048
 
2198
2049
    @display_command
2199
 
    def run(self, null=False, directory=u'.'):
2200
 
        wt = WorkingTree.open_containing(directory)[0]
2201
 
        self.add_cleanup(wt.lock_read().unlock)
2202
 
        basis = wt.basis_tree()
2203
 
        self.add_cleanup(basis.lock_read().unlock)
2204
 
        basis_inv = basis.inventory
2205
 
        inv = wt.inventory
2206
 
        for file_id in inv:
2207
 
            if basis_inv.has_id(file_id):
2208
 
                continue
2209
 
            if inv.is_root(file_id) and len(basis_inv) == 0:
2210
 
                continue
2211
 
            path = inv.id2path(file_id)
2212
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2213
 
                continue
2214
 
            if null:
2215
 
                self.outf.write(path + '\0')
2216
 
            else:
2217
 
                self.outf.write(osutils.quotefn(path) + '\n')
 
2050
    def run(self, null=False):
 
2051
        wt = WorkingTree.open_containing(u'.')[0]
 
2052
        wt.lock_read()
 
2053
        try:
 
2054
            basis = wt.basis_tree()
 
2055
            basis.lock_read()
 
2056
            try:
 
2057
                basis_inv = basis.inventory
 
2058
                inv = wt.inventory
 
2059
                for file_id in inv:
 
2060
                    if file_id in basis_inv:
 
2061
                        continue
 
2062
                    if inv.is_root(file_id) and len(basis_inv) == 0:
 
2063
                        continue
 
2064
                    path = inv.id2path(file_id)
 
2065
                    if not os.access(osutils.abspath(path), os.F_OK):
 
2066
                        continue
 
2067
                    if null:
 
2068
                        self.outf.write(path + '\0')
 
2069
                    else:
 
2070
                        self.outf.write(osutils.quotefn(path) + '\n')
 
2071
            finally:
 
2072
                basis.unlock()
 
2073
        finally:
 
2074
            wt.unlock()
2218
2075
 
2219
2076
 
2220
2077
class cmd_root(Command):
2221
 
    __doc__ = """Show the tree root directory.
 
2078
    """Show the tree root directory.
2222
2079
 
2223
2080
    The root is the nearest enclosing directory with a .bzr control
2224
2081
    directory."""
2235
2092
    try:
2236
2093
        return int(limitstring)
2237
2094
    except ValueError:
2238
 
        msg = gettext("The limit argument must be an integer.")
 
2095
        msg = "The limit argument must be an integer."
2239
2096
        raise errors.BzrCommandError(msg)
2240
2097
 
2241
2098
 
2243
2100
    try:
2244
2101
        return int(s)
2245
2102
    except ValueError:
2246
 
        msg = gettext("The levels argument must be an integer.")
 
2103
        msg = "The levels argument must be an integer."
2247
2104
        raise errors.BzrCommandError(msg)
2248
2105
 
2249
2106
 
2250
2107
class cmd_log(Command):
2251
 
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2108
    """Show historical log for a branch or subset of a branch.
2252
2109
 
2253
2110
    log is bzr's default tool for exploring the history of a branch.
2254
2111
    The branch to use is taken from the first parameter. If no parameters
2359
2216
 
2360
2217
    :Other filtering:
2361
2218
 
2362
 
      The --match option can be used for finding revisions that match a
2363
 
      regular expression in a commit message, committer, author or bug.
2364
 
      Specifying the option several times will match any of the supplied
2365
 
      expressions. --match-author, --match-bugs, --match-committer and
2366
 
      --match-message can be used to only match a specific field.
 
2219
      The --message option can be used for finding revisions that match a
 
2220
      regular expression in a commit message.
2367
2221
 
2368
2222
    :Tips & tricks:
2369
2223
 
2370
2224
      GUI tools and IDEs are often better at exploring history than command
2371
 
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2372
 
      bzr-explorer shell, or the Loggerhead web interface.  See the Plugin
2373
 
      Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2374
 
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
 
2225
      line tools. You may prefer qlog or glog from the QBzr and Bzr-Gtk packages
 
2226
      respectively for example. (TortoiseBzr uses qlog for displaying logs.) See
 
2227
      http://bazaar-vcs.org/BzrPlugins and http://bazaar-vcs.org/IDEIntegration.
 
2228
 
 
2229
      Web interfaces are often better at exploring history than command line
 
2230
      tools, particularly for branches on servers. You may prefer Loggerhead
 
2231
      or one of its alternatives. See http://bazaar-vcs.org/WebInterface.
2375
2232
 
2376
2233
      You may find it useful to add the aliases below to ``bazaar.conf``::
2377
2234
 
2418
2275
                   help='Show just the specified revision.'
2419
2276
                   ' See also "help revisionspec".'),
2420
2277
            'log-format',
2421
 
            RegistryOption('authors',
2422
 
                'What names to list as authors - first, all or committer.',
2423
 
                title='Authors',
2424
 
                lazy_registry=('bzrlib.log', 'author_list_registry'),
2425
 
            ),
2426
2278
            Option('levels',
2427
2279
                   short_name='n',
2428
2280
                   help='Number of levels to display - 0 for all, 1 for flat.',
2429
2281
                   argname='N',
2430
2282
                   type=_parse_levels),
2431
2283
            Option('message',
 
2284
                   short_name='m',
2432
2285
                   help='Show revisions whose message matches this '
2433
2286
                        'regular expression.',
2434
 
                   type=str,
2435
 
                   hidden=True),
 
2287
                   type=str),
2436
2288
            Option('limit',
2437
2289
                   short_name='l',
2438
2290
                   help='Limit the output to the first N revisions.',
2441
2293
            Option('show-diff',
2442
2294
                   short_name='p',
2443
2295
                   help='Show changes made in each revision as a patch.'),
2444
 
            Option('include-merged',
 
2296
            Option('include-merges',
2445
2297
                   help='Show merged revisions like --levels 0 does.'),
2446
 
            Option('include-merges', hidden=True,
2447
 
                   help='Historical alias for --include-merged.'),
2448
 
            Option('omit-merges',
2449
 
                   help='Do not report commits with more than one parent.'),
2450
 
            Option('exclude-common-ancestry',
2451
 
                   help='Display only the revisions that are not part'
2452
 
                   ' of both ancestries (require -rX..Y)'
2453
 
                   ),
2454
 
            Option('signatures',
2455
 
                   help='Show digital signature validity'),
2456
 
            ListOption('match',
2457
 
                short_name='m',
2458
 
                help='Show revisions whose properties match this '
2459
 
                'expression.',
2460
 
                type=str),
2461
 
            ListOption('match-message',
2462
 
                   help='Show revisions whose message matches this '
2463
 
                   'expression.',
2464
 
                type=str),
2465
 
            ListOption('match-committer',
2466
 
                   help='Show revisions whose committer matches this '
2467
 
                   'expression.',
2468
 
                type=str),
2469
 
            ListOption('match-author',
2470
 
                   help='Show revisions whose authors match this '
2471
 
                   'expression.',
2472
 
                type=str),
2473
 
            ListOption('match-bugs',
2474
 
                   help='Show revisions whose bugs match this '
2475
 
                   'expression.',
2476
 
                type=str)
2477
2298
            ]
2478
2299
    encoding_type = 'replace'
2479
2300
 
2489
2310
            message=None,
2490
2311
            limit=None,
2491
2312
            show_diff=False,
2492
 
            include_merged=None,
2493
 
            authors=None,
2494
 
            exclude_common_ancestry=False,
2495
 
            signatures=False,
2496
 
            match=None,
2497
 
            match_message=None,
2498
 
            match_committer=None,
2499
 
            match_author=None,
2500
 
            match_bugs=None,
2501
 
            omit_merges=False,
2502
 
            include_merges=symbol_versioning.DEPRECATED_PARAMETER,
2503
 
            ):
 
2313
            include_merges=False):
2504
2314
        from bzrlib.log import (
2505
2315
            Logger,
2506
2316
            make_log_request_dict,
2507
2317
            _get_info_for_log_files,
2508
2318
            )
2509
2319
        direction = (forward and 'forward') or 'reverse'
2510
 
        if symbol_versioning.deprecated_passed(include_merges):
2511
 
            ui.ui_factory.show_user_warning(
2512
 
                'deprecated_command_option',
2513
 
                deprecated_name='--include-merges',
2514
 
                recommended_name='--include-merged',
2515
 
                deprecated_in_version='2.5',
2516
 
                command=self.invoked_as)
2517
 
            if include_merged is None:
2518
 
                include_merged = include_merges
2519
 
            else:
2520
 
                raise errors.BzrCommandError(gettext(
2521
 
                    '{0} and {1} are mutually exclusive').format(
2522
 
                    '--include-merges', '--include-merged'))
2523
 
        if include_merged is None:
2524
 
            include_merged = False
2525
 
        if (exclude_common_ancestry
2526
 
            and (revision is None or len(revision) != 2)):
2527
 
            raise errors.BzrCommandError(gettext(
2528
 
                '--exclude-common-ancestry requires -r with two revisions'))
2529
 
        if include_merged:
 
2320
        if include_merges:
2530
2321
            if levels is None:
2531
2322
                levels = 0
2532
2323
            else:
2533
 
                raise errors.BzrCommandError(gettext(
2534
 
                    '{0} and {1} are mutually exclusive').format(
2535
 
                    '--levels', '--include-merged'))
 
2324
                raise errors.BzrCommandError(
 
2325
                    '--levels and --include-merges are mutually exclusive')
2536
2326
 
2537
2327
        if change is not None:
2538
2328
            if len(change) > 1:
2539
2329
                raise errors.RangeInChangeOption()
2540
2330
            if revision is not None:
2541
 
                raise errors.BzrCommandError(gettext(
2542
 
                    '{0} and {1} are mutually exclusive').format(
2543
 
                    '--revision', '--change'))
 
2331
                raise errors.BzrCommandError(
 
2332
                    '--revision and --change are mutually exclusive')
2544
2333
            else:
2545
2334
                revision = change
2546
2335
 
2547
2336
        file_ids = []
2548
2337
        filter_by_dir = False
2549
 
        if file_list:
2550
 
            # find the file ids to log and check for directory filtering
2551
 
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2552
 
                revision, file_list, self.add_cleanup)
2553
 
            for relpath, file_id, kind in file_info_list:
2554
 
                if file_id is None:
2555
 
                    raise errors.BzrCommandError(gettext(
2556
 
                        "Path unknown at end or start of revision range: %s") %
2557
 
                        relpath)
2558
 
                # If the relpath is the top of the tree, we log everything
2559
 
                if relpath == '':
2560
 
                    file_ids = []
2561
 
                    break
 
2338
        b = None
 
2339
        try:
 
2340
            if file_list:
 
2341
                # find the file ids to log and check for directory filtering
 
2342
                b, file_info_list, rev1, rev2 = _get_info_for_log_files(
 
2343
                    revision, file_list)
 
2344
                for relpath, file_id, kind in file_info_list:
 
2345
                    if file_id is None:
 
2346
                        raise errors.BzrCommandError(
 
2347
                            "Path unknown at end or start of revision range: %s" %
 
2348
                            relpath)
 
2349
                    # If the relpath is the top of the tree, we log everything
 
2350
                    if relpath == '':
 
2351
                        file_ids = []
 
2352
                        break
 
2353
                    else:
 
2354
                        file_ids.append(file_id)
 
2355
                    filter_by_dir = filter_by_dir or (
 
2356
                        kind in ['directory', 'tree-reference'])
 
2357
            else:
 
2358
                # log everything
 
2359
                # FIXME ? log the current subdir only RBC 20060203
 
2360
                if revision is not None \
 
2361
                        and len(revision) > 0 and revision[0].get_branch():
 
2362
                    location = revision[0].get_branch()
2562
2363
                else:
2563
 
                    file_ids.append(file_id)
2564
 
                filter_by_dir = filter_by_dir or (
2565
 
                    kind in ['directory', 'tree-reference'])
2566
 
        else:
2567
 
            # log everything
2568
 
            # FIXME ? log the current subdir only RBC 20060203
2569
 
            if revision is not None \
2570
 
                    and len(revision) > 0 and revision[0].get_branch():
2571
 
                location = revision[0].get_branch()
2572
 
            else:
2573
 
                location = '.'
2574
 
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2575
 
            b = dir.open_branch()
2576
 
            self.add_cleanup(b.lock_read().unlock)
2577
 
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2578
 
 
2579
 
        if b.get_config().validate_signatures_in_log():
2580
 
            signatures = True
2581
 
 
2582
 
        if signatures:
2583
 
            if not gpg.GPGStrategy.verify_signatures_available():
2584
 
                raise errors.GpgmeNotInstalled(None)
2585
 
 
2586
 
        # Decide on the type of delta & diff filtering to use
2587
 
        # TODO: add an --all-files option to make this configurable & consistent
2588
 
        if not verbose:
2589
 
            delta_type = None
2590
 
        else:
2591
 
            delta_type = 'full'
2592
 
        if not show_diff:
2593
 
            diff_type = None
2594
 
        elif file_ids:
2595
 
            diff_type = 'partial'
2596
 
        else:
2597
 
            diff_type = 'full'
2598
 
 
2599
 
        # Build the log formatter
2600
 
        if log_format is None:
2601
 
            log_format = log.log_formatter_registry.get_default(b)
2602
 
        # Make a non-encoding output to include the diffs - bug 328007
2603
 
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2604
 
        lf = log_format(show_ids=show_ids, to_file=self.outf,
2605
 
                        to_exact_file=unencoded_output,
2606
 
                        show_timezone=timezone,
2607
 
                        delta_format=get_verbosity_level(),
2608
 
                        levels=levels,
2609
 
                        show_advice=levels is None,
2610
 
                        author_list_handler=authors)
2611
 
 
2612
 
        # Choose the algorithm for doing the logging. It's annoying
2613
 
        # having multiple code paths like this but necessary until
2614
 
        # the underlying repository format is faster at generating
2615
 
        # deltas or can provide everything we need from the indices.
2616
 
        # The default algorithm - match-using-deltas - works for
2617
 
        # multiple files and directories and is faster for small
2618
 
        # amounts of history (200 revisions say). However, it's too
2619
 
        # slow for logging a single file in a repository with deep
2620
 
        # history, i.e. > 10K revisions. In the spirit of "do no
2621
 
        # evil when adding features", we continue to use the
2622
 
        # original algorithm - per-file-graph - for the "single
2623
 
        # file that isn't a directory without showing a delta" case.
2624
 
        partial_history = revision and b.repository._format.supports_chks
2625
 
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2626
 
            or delta_type or partial_history)
2627
 
 
2628
 
        match_dict = {}
2629
 
        if match:
2630
 
            match_dict[''] = match
2631
 
        if match_message:
2632
 
            match_dict['message'] = match_message
2633
 
        if match_committer:
2634
 
            match_dict['committer'] = match_committer
2635
 
        if match_author:
2636
 
            match_dict['author'] = match_author
2637
 
        if match_bugs:
2638
 
            match_dict['bugs'] = match_bugs
2639
 
 
2640
 
        # Build the LogRequest and execute it
2641
 
        if len(file_ids) == 0:
2642
 
            file_ids = None
2643
 
        rqst = make_log_request_dict(
2644
 
            direction=direction, specific_fileids=file_ids,
2645
 
            start_revision=rev1, end_revision=rev2, limit=limit,
2646
 
            message_search=message, delta_type=delta_type,
2647
 
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2648
 
            exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
2649
 
            signature=signatures, omit_merges=omit_merges,
2650
 
            )
2651
 
        Logger(b, rqst).show(lf)
 
2364
                    location = '.'
 
2365
                dir, relpath = bzrdir.BzrDir.open_containing(location)
 
2366
                b = dir.open_branch()
 
2367
                b.lock_read()
 
2368
                rev1, rev2 = _get_revision_range(revision, b, self.name())
 
2369
 
 
2370
            # Decide on the type of delta & diff filtering to use
 
2371
            # TODO: add an --all-files option to make this configurable & consistent
 
2372
            if not verbose:
 
2373
                delta_type = None
 
2374
            else:
 
2375
                delta_type = 'full'
 
2376
            if not show_diff:
 
2377
                diff_type = None
 
2378
            elif file_ids:
 
2379
                diff_type = 'partial'
 
2380
            else:
 
2381
                diff_type = 'full'
 
2382
 
 
2383
            # Build the log formatter
 
2384
            if log_format is None:
 
2385
                log_format = log.log_formatter_registry.get_default(b)
 
2386
            # Make a non-encoding output to include the diffs - bug 328007
 
2387
            unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
 
2388
            lf = log_format(show_ids=show_ids, to_file=self.outf,
 
2389
                            to_exact_file=unencoded_output,
 
2390
                            show_timezone=timezone,
 
2391
                            delta_format=get_verbosity_level(),
 
2392
                            levels=levels,
 
2393
                            show_advice=levels is None)
 
2394
 
 
2395
            # Choose the algorithm for doing the logging. It's annoying
 
2396
            # having multiple code paths like this but necessary until
 
2397
            # the underlying repository format is faster at generating
 
2398
            # deltas or can provide everything we need from the indices.
 
2399
            # The default algorithm - match-using-deltas - works for
 
2400
            # multiple files and directories and is faster for small
 
2401
            # amounts of history (200 revisions say). However, it's too
 
2402
            # slow for logging a single file in a repository with deep
 
2403
            # history, i.e. > 10K revisions. In the spirit of "do no
 
2404
            # evil when adding features", we continue to use the
 
2405
            # original algorithm - per-file-graph - for the "single
 
2406
            # file that isn't a directory without showing a delta" case.
 
2407
            partial_history = revision and b.repository._format.supports_chks
 
2408
            match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2409
                or delta_type or partial_history)
 
2410
 
 
2411
            # Build the LogRequest and execute it
 
2412
            if len(file_ids) == 0:
 
2413
                file_ids = None
 
2414
            rqst = make_log_request_dict(
 
2415
                direction=direction, specific_fileids=file_ids,
 
2416
                start_revision=rev1, end_revision=rev2, limit=limit,
 
2417
                message_search=message, delta_type=delta_type,
 
2418
                diff_type=diff_type, _match_using_deltas=match_using_deltas)
 
2419
            Logger(b, rqst).show(lf)
 
2420
        finally:
 
2421
            if b is not None:
 
2422
                b.unlock()
2652
2423
 
2653
2424
 
2654
2425
def _get_revision_range(revisionspec_list, branch, command_name):
2669
2440
            # b is taken from revision[0].get_branch(), and
2670
2441
            # show_log will use its revision_history. Having
2671
2442
            # different branches will lead to weird behaviors.
2672
 
            raise errors.BzrCommandError(gettext(
 
2443
            raise errors.BzrCommandError(
2673
2444
                "bzr %s doesn't accept two revisions in different"
2674
 
                " branches.") % command_name)
2675
 
        if start_spec.spec is None:
2676
 
            # Avoid loading all the history.
2677
 
            rev1 = RevisionInfo(branch, None, None)
2678
 
        else:
2679
 
            rev1 = start_spec.in_history(branch)
 
2445
                " branches." % command_name)
 
2446
        rev1 = start_spec.in_history(branch)
2680
2447
        # Avoid loading all of history when we know a missing
2681
2448
        # end of range means the last revision ...
2682
2449
        if end_spec.spec is None:
2685
2452
        else:
2686
2453
            rev2 = end_spec.in_history(branch)
2687
2454
    else:
2688
 
        raise errors.BzrCommandError(gettext(
2689
 
            'bzr %s --revision takes one or two values.') % command_name)
 
2455
        raise errors.BzrCommandError(
 
2456
            'bzr %s --revision takes one or two values.' % command_name)
2690
2457
    return rev1, rev2
2691
2458
 
2692
2459
 
2711
2478
 
2712
2479
 
2713
2480
class cmd_touching_revisions(Command):
2714
 
    __doc__ = """Return revision-ids which affected a particular file.
 
2481
    """Return revision-ids which affected a particular file.
2715
2482
 
2716
2483
    A more user-friendly interface is "bzr log FILE".
2717
2484
    """
2724
2491
        tree, relpath = WorkingTree.open_containing(filename)
2725
2492
        file_id = tree.path2id(relpath)
2726
2493
        b = tree.branch
2727
 
        self.add_cleanup(b.lock_read().unlock)
2728
 
        touching_revs = log.find_touching_revisions(b, file_id)
2729
 
        for revno, revision_id, what in touching_revs:
2730
 
            self.outf.write("%6d %s\n" % (revno, what))
 
2494
        b.lock_read()
 
2495
        try:
 
2496
            touching_revs = log.find_touching_revisions(b, file_id)
 
2497
            for revno, revision_id, what in touching_revs:
 
2498
                self.outf.write("%6d %s\n" % (revno, what))
 
2499
        finally:
 
2500
            b.unlock()
2731
2501
 
2732
2502
 
2733
2503
class cmd_ls(Command):
2734
 
    __doc__ = """List files in a tree.
 
2504
    """List files in a tree.
2735
2505
    """
2736
2506
 
2737
2507
    _see_also = ['status', 'cat']
2743
2513
                   help='Recurse into subdirectories.'),
2744
2514
            Option('from-root',
2745
2515
                   help='Print paths relative to the root of the branch.'),
2746
 
            Option('unknown', short_name='u',
2747
 
                help='Print unknown files.'),
 
2516
            Option('unknown', help='Print unknown files.'),
2748
2517
            Option('versioned', help='Print versioned files.',
2749
2518
                   short_name='V'),
2750
 
            Option('ignored', short_name='i',
2751
 
                help='Print ignored files.'),
2752
 
            Option('kind', short_name='k',
 
2519
            Option('ignored', help='Print ignored files.'),
 
2520
            Option('null',
 
2521
                   help='Write an ascii NUL (\\0) separator '
 
2522
                   'between files rather than a newline.'),
 
2523
            Option('kind',
2753
2524
                   help='List entries of a particular kind: file, directory, symlink.',
2754
2525
                   type=unicode),
2755
 
            'null',
2756
2526
            'show-ids',
2757
 
            'directory',
2758
2527
            ]
2759
2528
    @display_command
2760
2529
    def run(self, revision=None, verbose=False,
2761
2530
            recursive=False, from_root=False,
2762
2531
            unknown=False, versioned=False, ignored=False,
2763
 
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2532
            null=False, kind=None, show_ids=False, path=None):
2764
2533
 
2765
2534
        if kind and kind not in ('file', 'directory', 'symlink'):
2766
 
            raise errors.BzrCommandError(gettext('invalid kind specified'))
 
2535
            raise errors.BzrCommandError('invalid kind specified')
2767
2536
 
2768
2537
        if verbose and null:
2769
 
            raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
 
2538
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
2770
2539
        all = not (unknown or versioned or ignored)
2771
2540
 
2772
2541
        selection = {'I':ignored, '?':unknown, 'V':versioned}
2775
2544
            fs_path = '.'
2776
2545
        else:
2777
2546
            if from_root:
2778
 
                raise errors.BzrCommandError(gettext('cannot specify both --from-root'
2779
 
                                             ' and PATH'))
 
2547
                raise errors.BzrCommandError('cannot specify both --from-root'
 
2548
                                             ' and PATH')
2780
2549
            fs_path = path
2781
 
        tree, branch, relpath = \
2782
 
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2550
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2551
            fs_path)
2783
2552
 
2784
2553
        # Calculate the prefix to use
2785
2554
        prefix = None
2798
2567
            if view_files:
2799
2568
                apply_view = True
2800
2569
                view_str = views.view_display_str(view_files)
2801
 
                note(gettext("Ignoring files outside view. View is %s") % view_str)
2802
 
 
2803
 
        self.add_cleanup(tree.lock_read().unlock)
2804
 
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2805
 
            from_dir=relpath, recursive=recursive):
2806
 
            # Apply additional masking
2807
 
            if not all and not selection[fc]:
2808
 
                continue
2809
 
            if kind is not None and fkind != kind:
2810
 
                continue
2811
 
            if apply_view:
2812
 
                try:
2813
 
                    if relpath:
2814
 
                        fullpath = osutils.pathjoin(relpath, fp)
2815
 
                    else:
2816
 
                        fullpath = fp
2817
 
                    views.check_path_in_view(tree, fullpath)
2818
 
                except errors.FileOutsideView:
2819
 
                    continue
2820
 
 
2821
 
            # Output the entry
2822
 
            if prefix:
2823
 
                fp = osutils.pathjoin(prefix, fp)
2824
 
            kindch = entry.kind_character()
2825
 
            outstring = fp + kindch
2826
 
            ui.ui_factory.clear_term()
2827
 
            if verbose:
2828
 
                outstring = '%-8s %s' % (fc, outstring)
2829
 
                if show_ids and fid is not None:
2830
 
                    outstring = "%-50s %s" % (outstring, fid)
2831
 
                self.outf.write(outstring + '\n')
2832
 
            elif null:
2833
 
                self.outf.write(fp + '\0')
2834
 
                if show_ids:
2835
 
                    if fid is not None:
2836
 
                        self.outf.write(fid)
2837
 
                    self.outf.write('\0')
2838
 
                self.outf.flush()
2839
 
            else:
2840
 
                if show_ids:
2841
 
                    if fid is not None:
2842
 
                        my_id = fid
2843
 
                    else:
2844
 
                        my_id = ''
2845
 
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
2846
 
                else:
 
2570
                note("Ignoring files outside view. View is %s" % view_str)
 
2571
 
 
2572
        tree.lock_read()
 
2573
        try:
 
2574
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
2575
                from_dir=relpath, recursive=recursive):
 
2576
                # Apply additional masking
 
2577
                if not all and not selection[fc]:
 
2578
                    continue
 
2579
                if kind is not None and fkind != kind:
 
2580
                    continue
 
2581
                if apply_view:
 
2582
                    try:
 
2583
                        if relpath:
 
2584
                            fullpath = osutils.pathjoin(relpath, fp)
 
2585
                        else:
 
2586
                            fullpath = fp
 
2587
                        views.check_path_in_view(tree, fullpath)
 
2588
                    except errors.FileOutsideView:
 
2589
                        continue
 
2590
 
 
2591
                # Output the entry
 
2592
                if prefix:
 
2593
                    fp = osutils.pathjoin(prefix, fp)
 
2594
                kindch = entry.kind_character()
 
2595
                outstring = fp + kindch
 
2596
                ui.ui_factory.clear_term()
 
2597
                if verbose:
 
2598
                    outstring = '%-8s %s' % (fc, outstring)
 
2599
                    if show_ids and fid is not None:
 
2600
                        outstring = "%-50s %s" % (outstring, fid)
2847
2601
                    self.outf.write(outstring + '\n')
 
2602
                elif null:
 
2603
                    self.outf.write(fp + '\0')
 
2604
                    if show_ids:
 
2605
                        if fid is not None:
 
2606
                            self.outf.write(fid)
 
2607
                        self.outf.write('\0')
 
2608
                    self.outf.flush()
 
2609
                else:
 
2610
                    if show_ids:
 
2611
                        if fid is not None:
 
2612
                            my_id = fid
 
2613
                        else:
 
2614
                            my_id = ''
 
2615
                        self.outf.write('%-50s %s\n' % (outstring, my_id))
 
2616
                    else:
 
2617
                        self.outf.write(outstring + '\n')
 
2618
        finally:
 
2619
            tree.unlock()
2848
2620
 
2849
2621
 
2850
2622
class cmd_unknowns(Command):
2851
 
    __doc__ = """List unknown files.
 
2623
    """List unknown files.
2852
2624
    """
2853
2625
 
2854
2626
    hidden = True
2855
2627
    _see_also = ['ls']
2856
 
    takes_options = ['directory']
2857
2628
 
2858
2629
    @display_command
2859
 
    def run(self, directory=u'.'):
2860
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
2630
    def run(self):
 
2631
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
2861
2632
            self.outf.write(osutils.quotefn(f) + '\n')
2862
2633
 
2863
2634
 
2864
2635
class cmd_ignore(Command):
2865
 
    __doc__ = """Ignore specified files or patterns.
 
2636
    """Ignore specified files or patterns.
2866
2637
 
2867
2638
    See ``bzr help patterns`` for details on the syntax of patterns.
2868
2639
 
2876
2647
    After adding, editing or deleting that file either indirectly by
2877
2648
    using this command or directly by using an editor, be sure to commit
2878
2649
    it.
2879
 
    
2880
 
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2881
 
    the global ignore file can be found in the application data directory as
2882
 
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2883
 
    Global ignores are not touched by this command. The global ignore file
2884
 
    can be edited directly using an editor.
2885
 
 
2886
 
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2887
 
    precedence over regular ignores.  Such exceptions are used to specify
2888
 
    files that should be versioned which would otherwise be ignored.
2889
 
    
2890
 
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2891
 
    precedence over the '!' exception patterns.
2892
 
 
2893
 
    :Notes: 
2894
 
        
2895
 
    * Ignore patterns containing shell wildcards must be quoted from
2896
 
      the shell on Unix.
2897
 
 
2898
 
    * Ignore patterns starting with "#" act as comments in the ignore file.
2899
 
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
2650
 
 
2651
    Note: ignore patterns containing shell wildcards must be quoted from
 
2652
    the shell on Unix.
2900
2653
 
2901
2654
    :Examples:
2902
2655
        Ignore the top level Makefile::
2903
2656
 
2904
2657
            bzr ignore ./Makefile
2905
2658
 
2906
 
        Ignore .class files in all directories...::
 
2659
        Ignore class files in all directories::
2907
2660
 
2908
2661
            bzr ignore "*.class"
2909
2662
 
2910
 
        ...but do not ignore "special.class"::
2911
 
 
2912
 
            bzr ignore "!special.class"
2913
 
 
2914
 
        Ignore files whose name begins with the "#" character::
2915
 
 
2916
 
            bzr ignore "RE:^#"
2917
 
 
2918
2663
        Ignore .o files under the lib directory::
2919
2664
 
2920
2665
            bzr ignore "lib/**/*.o"
2926
2671
        Ignore everything but the "debian" toplevel directory::
2927
2672
 
2928
2673
            bzr ignore "RE:(?!debian/).*"
2929
 
        
2930
 
        Ignore everything except the "local" toplevel directory,
2931
 
        but always ignore autosave files ending in ~, even under local/::
2932
 
        
2933
 
            bzr ignore "*"
2934
 
            bzr ignore "!./local"
2935
 
            bzr ignore "!!*~"
2936
2674
    """
2937
2675
 
2938
2676
    _see_also = ['status', 'ignored', 'patterns']
2939
2677
    takes_args = ['name_pattern*']
2940
 
    takes_options = ['directory',
2941
 
        Option('default-rules',
2942
 
               help='Display the default ignore rules that bzr uses.')
 
2678
    takes_options = [
 
2679
        Option('old-default-rules',
 
2680
               help='Write out the ignore rules bzr < 0.9 always used.')
2943
2681
        ]
2944
2682
 
2945
 
    def run(self, name_pattern_list=None, default_rules=None,
2946
 
            directory=u'.'):
 
2683
    def run(self, name_pattern_list=None, old_default_rules=None):
2947
2684
        from bzrlib import ignores
2948
 
        if default_rules is not None:
2949
 
            # dump the default rules and exit
2950
 
            for pattern in ignores.USER_DEFAULTS:
2951
 
                self.outf.write("%s\n" % pattern)
 
2685
        if old_default_rules is not None:
 
2686
            # dump the rules and exit
 
2687
            for pattern in ignores.OLD_DEFAULTS:
 
2688
                print pattern
2952
2689
            return
2953
2690
        if not name_pattern_list:
2954
 
            raise errors.BzrCommandError(gettext("ignore requires at least one "
2955
 
                "NAME_PATTERN or --default-rules."))
 
2691
            raise errors.BzrCommandError("ignore requires at least one "
 
2692
                                  "NAME_PATTERN or --old-default-rules")
2956
2693
        name_pattern_list = [globbing.normalize_pattern(p)
2957
2694
                             for p in name_pattern_list]
2958
 
        bad_patterns = ''
2959
 
        bad_patterns_count = 0
2960
 
        for p in name_pattern_list:
2961
 
            if not globbing.Globster.is_pattern_valid(p):
2962
 
                bad_patterns_count += 1
2963
 
                bad_patterns += ('\n  %s' % p)
2964
 
        if bad_patterns:
2965
 
            msg = (ngettext('Invalid ignore pattern found. %s', 
2966
 
                            'Invalid ignore patterns found. %s',
2967
 
                            bad_patterns_count) % bad_patterns)
2968
 
            ui.ui_factory.show_error(msg)
2969
 
            raise errors.InvalidPattern('')
2970
2695
        for name_pattern in name_pattern_list:
2971
2696
            if (name_pattern[0] == '/' or
2972
2697
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2973
 
                raise errors.BzrCommandError(gettext(
2974
 
                    "NAME_PATTERN should not be an absolute path"))
2975
 
        tree, relpath = WorkingTree.open_containing(directory)
 
2698
                raise errors.BzrCommandError(
 
2699
                    "NAME_PATTERN should not be an absolute path")
 
2700
        tree, relpath = WorkingTree.open_containing(u'.')
2976
2701
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2977
2702
        ignored = globbing.Globster(name_pattern_list)
2978
2703
        matches = []
2979
 
        self.add_cleanup(tree.lock_read().unlock)
 
2704
        tree.lock_read()
2980
2705
        for entry in tree.list_files():
2981
2706
            id = entry[3]
2982
2707
            if id is not None:
2983
2708
                filename = entry[0]
2984
2709
                if ignored.match(filename):
2985
 
                    matches.append(filename)
 
2710
                    matches.append(filename.encode('utf-8'))
 
2711
        tree.unlock()
2986
2712
        if len(matches) > 0:
2987
 
            self.outf.write(gettext("Warning: the following files are version "
2988
 
                  "controlled and match your ignore pattern:\n%s"
2989
 
                  "\nThese files will continue to be version controlled"
2990
 
                  " unless you 'bzr remove' them.\n") % ("\n".join(matches),))
 
2713
            print "Warning: the following files are version controlled and" \
 
2714
                  " match your ignore pattern:\n%s" \
 
2715
                  "\nThese files will continue to be version controlled" \
 
2716
                  " unless you 'bzr remove' them." % ("\n".join(matches),)
2991
2717
 
2992
2718
 
2993
2719
class cmd_ignored(Command):
2994
 
    __doc__ = """List ignored files and the patterns that matched them.
 
2720
    """List ignored files and the patterns that matched them.
2995
2721
 
2996
2722
    List all the ignored files and the ignore pattern that caused the file to
2997
2723
    be ignored.
3003
2729
 
3004
2730
    encoding_type = 'replace'
3005
2731
    _see_also = ['ignore', 'ls']
3006
 
    takes_options = ['directory']
3007
2732
 
3008
2733
    @display_command
3009
 
    def run(self, directory=u'.'):
3010
 
        tree = WorkingTree.open_containing(directory)[0]
3011
 
        self.add_cleanup(tree.lock_read().unlock)
3012
 
        for path, file_class, kind, file_id, entry in tree.list_files():
3013
 
            if file_class != 'I':
3014
 
                continue
3015
 
            ## XXX: Slightly inefficient since this was already calculated
3016
 
            pat = tree.is_ignored(path)
3017
 
            self.outf.write('%-50s %s\n' % (path, pat))
 
2734
    def run(self):
 
2735
        tree = WorkingTree.open_containing(u'.')[0]
 
2736
        tree.lock_read()
 
2737
        try:
 
2738
            for path, file_class, kind, file_id, entry in tree.list_files():
 
2739
                if file_class != 'I':
 
2740
                    continue
 
2741
                ## XXX: Slightly inefficient since this was already calculated
 
2742
                pat = tree.is_ignored(path)
 
2743
                self.outf.write('%-50s %s\n' % (path, pat))
 
2744
        finally:
 
2745
            tree.unlock()
3018
2746
 
3019
2747
 
3020
2748
class cmd_lookup_revision(Command):
3021
 
    __doc__ = """Lookup the revision-id from a revision-number
 
2749
    """Lookup the revision-id from a revision-number
3022
2750
 
3023
2751
    :Examples:
3024
2752
        bzr lookup-revision 33
3025
2753
    """
3026
2754
    hidden = True
3027
2755
    takes_args = ['revno']
3028
 
    takes_options = ['directory']
3029
2756
 
3030
2757
    @display_command
3031
 
    def run(self, revno, directory=u'.'):
 
2758
    def run(self, revno):
3032
2759
        try:
3033
2760
            revno = int(revno)
3034
2761
        except ValueError:
3035
 
            raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
3036
 
                                         % revno)
3037
 
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
3038
 
        self.outf.write("%s\n" % revid)
 
2762
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
 
2763
 
 
2764
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
3039
2765
 
3040
2766
 
3041
2767
class cmd_export(Command):
3042
 
    __doc__ = """Export current or past revision to a destination directory or archive.
 
2768
    """Export current or past revision to a destination directory or archive.
3043
2769
 
3044
2770
    If no revision is specified this exports the last committed revision.
3045
2771
 
3066
2792
         zip                          .zip
3067
2793
      =================       =========================
3068
2794
    """
3069
 
    encoding = 'exact'
3070
2795
    takes_args = ['dest', 'branch_or_subdir?']
3071
 
    takes_options = ['directory',
 
2796
    takes_options = [
3072
2797
        Option('format',
3073
2798
               help="Type of file to export to.",
3074
2799
               type=unicode),
3078
2803
        Option('root',
3079
2804
               type=str,
3080
2805
               help="Name of the root directory inside the exported file."),
3081
 
        Option('per-file-timestamps',
3082
 
               help='Set modification time of files to that of the last '
3083
 
                    'revision in which it was changed.'),
3084
2806
        ]
3085
2807
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
3086
 
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
 
2808
        root=None, filters=False):
3087
2809
        from bzrlib.export import export
3088
2810
 
3089
2811
        if branch_or_subdir is None:
3090
 
            tree = WorkingTree.open_containing(directory)[0]
 
2812
            tree = WorkingTree.open_containing(u'.')[0]
3091
2813
            b = tree.branch
3092
2814
            subdir = None
3093
2815
        else:
3096
2818
 
3097
2819
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
3098
2820
        try:
3099
 
            export(rev_tree, dest, format, root, subdir, filtered=filters,
3100
 
                   per_file_timestamps=per_file_timestamps)
 
2821
            export(rev_tree, dest, format, root, subdir, filtered=filters)
3101
2822
        except errors.NoSuchExportFormat, e:
3102
 
            raise errors.BzrCommandError(gettext('Unsupported export format: %s') % e.format)
 
2823
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3103
2824
 
3104
2825
 
3105
2826
class cmd_cat(Command):
3106
 
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
2827
    """Write the contents of a file as of a given revision to standard output.
3107
2828
 
3108
2829
    If no revision is nominated, the last revision is used.
3109
2830
 
3112
2833
    """
3113
2834
 
3114
2835
    _see_also = ['ls']
3115
 
    takes_options = ['directory',
 
2836
    takes_options = [
3116
2837
        Option('name-from-revision', help='The path name in the old tree.'),
3117
2838
        Option('filters', help='Apply content filters to display the '
3118
2839
                'convenience form.'),
3123
2844
 
3124
2845
    @display_command
3125
2846
    def run(self, filename, revision=None, name_from_revision=False,
3126
 
            filters=False, directory=None):
 
2847
            filters=False):
3127
2848
        if revision is not None and len(revision) != 1:
3128
 
            raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3129
 
                                         " one revision specifier"))
 
2849
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
 
2850
                                         " one revision specifier")
3130
2851
        tree, branch, relpath = \
3131
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
3132
 
        self.add_cleanup(branch.lock_read().unlock)
3133
 
        return self._run(tree, branch, relpath, filename, revision,
3134
 
                         name_from_revision, filters)
 
2852
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2853
        branch.lock_read()
 
2854
        try:
 
2855
            return self._run(tree, branch, relpath, filename, revision,
 
2856
                             name_from_revision, filters)
 
2857
        finally:
 
2858
            branch.unlock()
3135
2859
 
3136
2860
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
3137
2861
        filtered):
3138
2862
        if tree is None:
3139
2863
            tree = b.basis_tree()
3140
2864
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3141
 
        self.add_cleanup(rev_tree.lock_read().unlock)
3142
2865
 
3143
2866
        old_file_id = rev_tree.path2id(relpath)
3144
2867
 
3145
 
        # TODO: Split out this code to something that generically finds the
3146
 
        # best id for a path across one or more trees; it's like
3147
 
        # find_ids_across_trees but restricted to find just one. -- mbp
3148
 
        # 20110705.
3149
2868
        if name_from_revision:
3150
2869
            # Try in revision if requested
3151
2870
            if old_file_id is None:
3152
 
                raise errors.BzrCommandError(gettext(
3153
 
                    "{0!r} is not present in revision {1}").format(
 
2871
                raise errors.BzrCommandError(
 
2872
                    "%r is not present in revision %s" % (
3154
2873
                        filename, rev_tree.get_revision_id()))
3155
2874
            else:
3156
 
                actual_file_id = old_file_id
 
2875
                content = rev_tree.get_file_text(old_file_id)
3157
2876
        else:
3158
2877
            cur_file_id = tree.path2id(relpath)
3159
 
            if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3160
 
                actual_file_id = cur_file_id
3161
 
            elif old_file_id is not None:
3162
 
                actual_file_id = old_file_id
3163
 
            else:
3164
 
                raise errors.BzrCommandError(gettext(
3165
 
                    "{0!r} is not present in revision {1}").format(
 
2878
            found = False
 
2879
            if cur_file_id is not None:
 
2880
                # Then try with the actual file id
 
2881
                try:
 
2882
                    content = rev_tree.get_file_text(cur_file_id)
 
2883
                    found = True
 
2884
                except errors.NoSuchId:
 
2885
                    # The actual file id didn't exist at that time
 
2886
                    pass
 
2887
            if not found and old_file_id is not None:
 
2888
                # Finally try with the old file id
 
2889
                content = rev_tree.get_file_text(old_file_id)
 
2890
                found = True
 
2891
            if not found:
 
2892
                # Can't be found anywhere
 
2893
                raise errors.BzrCommandError(
 
2894
                    "%r is not present in revision %s" % (
3166
2895
                        filename, rev_tree.get_revision_id()))
3167
2896
        if filtered:
3168
 
            from bzrlib.filter_tree import ContentFilterTree
3169
 
            filter_tree = ContentFilterTree(rev_tree,
3170
 
                rev_tree._content_filter_stack)
3171
 
            content = filter_tree.get_file_text(actual_file_id)
 
2897
            from bzrlib.filters import (
 
2898
                ContentFilterContext,
 
2899
                filtered_output_bytes,
 
2900
                )
 
2901
            filters = rev_tree._content_filter_stack(relpath)
 
2902
            chunks = content.splitlines(True)
 
2903
            content = filtered_output_bytes(chunks, filters,
 
2904
                ContentFilterContext(relpath, rev_tree))
 
2905
            self.outf.writelines(content)
3172
2906
        else:
3173
 
            content = rev_tree.get_file_text(actual_file_id)
3174
 
        self.cleanup_now()
3175
 
        self.outf.write(content)
 
2907
            self.outf.write(content)
3176
2908
 
3177
2909
 
3178
2910
class cmd_local_time_offset(Command):
3179
 
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
2911
    """Show the offset in seconds from GMT to local time."""
3180
2912
    hidden = True
3181
2913
    @display_command
3182
2914
    def run(self):
3183
 
        self.outf.write("%s\n" % osutils.local_time_offset())
 
2915
        print osutils.local_time_offset()
3184
2916
 
3185
2917
 
3186
2918
 
3187
2919
class cmd_commit(Command):
3188
 
    __doc__ = """Commit changes into a new revision.
 
2920
    """Commit changes into a new revision.
3189
2921
 
3190
2922
    An explanatory message needs to be given for each commit. This is
3191
2923
    often done by using the --message option (getting the message from the
3239
2971
      to trigger updates to external systems like bug trackers. The --fixes
3240
2972
      option can be used to record the association between a revision and
3241
2973
      one or more bugs. See ``bzr help bugs`` for details.
 
2974
 
 
2975
      A selective commit may fail in some cases where the committed
 
2976
      tree would be invalid. Consider::
 
2977
  
 
2978
        bzr init foo
 
2979
        mkdir foo/bar
 
2980
        bzr add foo/bar
 
2981
        bzr commit foo -m "committing foo"
 
2982
        bzr mv foo/bar foo/baz
 
2983
        mkdir foo/bar
 
2984
        bzr add foo/bar
 
2985
        bzr commit foo/bar -m "committing bar but not baz"
 
2986
  
 
2987
      In the example above, the last commit will fail by design. This gives
 
2988
      the user the opportunity to decide whether they want to commit the
 
2989
      rename at the same time, separately first, or not at all. (As a general
 
2990
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
3242
2991
    """
 
2992
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
2993
 
 
2994
    # TODO: Strict commit that fails if there are deleted files.
 
2995
    #       (what does "deleted files" mean ??)
 
2996
 
 
2997
    # TODO: Give better message for -s, --summary, used by tla people
 
2998
 
 
2999
    # XXX: verbose currently does nothing
3243
3000
 
3244
3001
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
3245
3002
    takes_args = ['selected*']
3274
3031
                         "the master branch until a normal commit "
3275
3032
                         "is performed."
3276
3033
                    ),
3277
 
             Option('show-diff', short_name='p',
 
3034
             Option('show-diff',
3278
3035
                    help='When no message is supplied, show the diff along'
3279
3036
                    ' with the status summary in the message editor.'),
3280
 
             Option('lossy', 
3281
 
                    help='When committing to a foreign version control '
3282
 
                    'system do not push data that can not be natively '
3283
 
                    'represented.'),
3284
3037
             ]
3285
3038
    aliases = ['ci', 'checkin']
3286
3039
 
3287
3040
    def _iter_bug_fix_urls(self, fixes, branch):
3288
 
        default_bugtracker  = None
3289
3041
        # Configure the properties for bug fixing attributes.
3290
3042
        for fixed_bug in fixes:
3291
3043
            tokens = fixed_bug.split(':')
3292
 
            if len(tokens) == 1:
3293
 
                if default_bugtracker is None:
3294
 
                    branch_config = branch.get_config()
3295
 
                    default_bugtracker = branch_config.get_user_option(
3296
 
                        "bugtracker")
3297
 
                if default_bugtracker is None:
3298
 
                    raise errors.BzrCommandError(gettext(
3299
 
                        "No tracker specified for bug %s. Use the form "
3300
 
                        "'tracker:id' or specify a default bug tracker "
3301
 
                        "using the `bugtracker` option.\nSee "
3302
 
                        "\"bzr help bugs\" for more information on this "
3303
 
                        "feature. Commit refused.") % fixed_bug)
3304
 
                tag = default_bugtracker
3305
 
                bug_id = tokens[0]
3306
 
            elif len(tokens) != 2:
3307
 
                raise errors.BzrCommandError(gettext(
 
3044
            if len(tokens) != 2:
 
3045
                raise errors.BzrCommandError(
3308
3046
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
3309
3047
                    "See \"bzr help bugs\" for more information on this "
3310
 
                    "feature.\nCommit refused.") % fixed_bug)
3311
 
            else:
3312
 
                tag, bug_id = tokens
 
3048
                    "feature.\nCommit refused." % fixed_bug)
 
3049
            tag, bug_id = tokens
3313
3050
            try:
3314
3051
                yield bugtracker.get_bug_url(tag, branch, bug_id)
3315
3052
            except errors.UnknownBugTrackerAbbreviation:
3316
 
                raise errors.BzrCommandError(gettext(
3317
 
                    'Unrecognized bug %s. Commit refused.') % fixed_bug)
 
3053
                raise errors.BzrCommandError(
 
3054
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
3318
3055
            except errors.MalformedBugIdentifier, e:
3319
 
                raise errors.BzrCommandError(gettext(
3320
 
                    "%s\nCommit refused.") % (str(e),))
 
3056
                raise errors.BzrCommandError(
 
3057
                    "%s\nCommit refused." % (str(e),))
3321
3058
 
3322
3059
    def run(self, message=None, file=None, verbose=False, selected_list=None,
3323
3060
            unchanged=False, strict=False, local=False, fixes=None,
3324
 
            author=None, show_diff=False, exclude=None, commit_time=None,
3325
 
            lossy=False):
 
3061
            author=None, show_diff=False, exclude=None, commit_time=None):
3326
3062
        from bzrlib.errors import (
3327
3063
            PointlessCommit,
3328
3064
            ConflictsInTree,
3331
3067
        from bzrlib.msgeditor import (
3332
3068
            edit_commit_message_encoded,
3333
3069
            generate_commit_message_template,
3334
 
            make_commit_message_template_encoded,
3335
 
            set_commit_message,
 
3070
            make_commit_message_template_encoded
3336
3071
        )
3337
3072
 
3338
3073
        commit_stamp = offset = None
3340
3075
            try:
3341
3076
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3342
3077
            except ValueError, e:
3343
 
                raise errors.BzrCommandError(gettext(
3344
 
                    "Could not parse --commit-time: " + str(e)))
 
3078
                raise errors.BzrCommandError(
 
3079
                    "Could not parse --commit-time: " + str(e))
 
3080
 
 
3081
        # TODO: Need a blackbox test for invoking the external editor; may be
 
3082
        # slightly problematic to run this cross-platform.
 
3083
 
 
3084
        # TODO: do more checks that the commit will succeed before
 
3085
        # spending the user's valuable time typing a commit message.
3345
3086
 
3346
3087
        properties = {}
3347
3088
 
3348
 
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
3089
        tree, selected_list = tree_files(selected_list)
3349
3090
        if selected_list == ['']:
3350
3091
            # workaround - commit of root of tree should be exactly the same
3351
3092
            # as just default commit in that tree, and succeed even though
3376
3117
                    '(use --file "%(f)s" to take commit message from that file)'
3377
3118
                    % { 'f': message })
3378
3119
                ui.ui_factory.show_warning(warning_msg)
3379
 
            if '\r' in message:
3380
 
                message = message.replace('\r\n', '\n')
3381
 
                message = message.replace('\r', '\n')
3382
 
            if file:
3383
 
                raise errors.BzrCommandError(gettext(
3384
 
                    "please specify either --message or --file"))
3385
3120
 
3386
3121
        def get_message(commit_obj):
3387
3122
            """Callback to get commit message"""
3388
 
            if file:
3389
 
                f = open(file)
3390
 
                try:
3391
 
                    my_message = f.read().decode(osutils.get_user_encoding())
3392
 
                finally:
3393
 
                    f.close()
3394
 
            elif message is not None:
3395
 
                my_message = message
3396
 
            else:
3397
 
                # No message supplied: make one up.
3398
 
                # text is the status of the tree
3399
 
                text = make_commit_message_template_encoded(tree,
 
3123
            my_message = message
 
3124
            if my_message is not None and '\r' in my_message:
 
3125
                my_message = my_message.replace('\r\n', '\n')
 
3126
                my_message = my_message.replace('\r', '\n')
 
3127
            if my_message is None and not file:
 
3128
                t = make_commit_message_template_encoded(tree,
3400
3129
                        selected_list, diff=show_diff,
3401
3130
                        output_encoding=osutils.get_user_encoding())
3402
 
                # start_message is the template generated from hooks
3403
 
                # XXX: Warning - looks like hooks return unicode,
3404
 
                # make_commit_message_template_encoded returns user encoding.
3405
 
                # We probably want to be using edit_commit_message instead to
3406
 
                # avoid this.
3407
 
                my_message = set_commit_message(commit_obj)
3408
 
                if my_message is None:
3409
 
                    start_message = generate_commit_message_template(commit_obj)
3410
 
                    my_message = edit_commit_message_encoded(text,
3411
 
                        start_message=start_message)
3412
 
                if my_message is None:
3413
 
                    raise errors.BzrCommandError(gettext("please specify a commit"
3414
 
                        " message with either --message or --file"))
3415
 
                if my_message == "":
3416
 
                    raise errors.BzrCommandError(gettext("Empty commit message specified."
3417
 
                            " Please specify a commit message with either"
3418
 
                            " --message or --file or leave a blank message"
3419
 
                            " with --message \"\"."))
 
3131
                start_message = generate_commit_message_template(commit_obj)
 
3132
                my_message = edit_commit_message_encoded(t,
 
3133
                    start_message=start_message)
 
3134
                if my_message is None:
 
3135
                    raise errors.BzrCommandError("please specify a commit"
 
3136
                        " message with either --message or --file")
 
3137
            elif my_message and file:
 
3138
                raise errors.BzrCommandError(
 
3139
                    "please specify either --message or --file")
 
3140
            if file:
 
3141
                my_message = codecs.open(file, 'rt',
 
3142
                                         osutils.get_user_encoding()).read()
 
3143
            if my_message == "":
 
3144
                raise errors.BzrCommandError("empty commit message specified")
3420
3145
            return my_message
3421
3146
 
3422
3147
        # The API permits a commit with a filter of [] to mean 'select nothing'
3430
3155
                        reporter=None, verbose=verbose, revprops=properties,
3431
3156
                        authors=author, timestamp=commit_stamp,
3432
3157
                        timezone=offset,
3433
 
                        exclude=tree.safe_relpath_files(exclude),
3434
 
                        lossy=lossy)
 
3158
                        exclude=safe_relpath_files(tree, exclude))
3435
3159
        except PointlessCommit:
3436
 
            raise errors.BzrCommandError(gettext("No changes to commit."
3437
 
                " Please 'bzr add' the files you want to commit, or use"
3438
 
                " --unchanged to force an empty commit."))
 
3160
            # FIXME: This should really happen before the file is read in;
 
3161
            # perhaps prepare the commit; get the message; then actually commit
 
3162
            raise errors.BzrCommandError("No changes to commit."
 
3163
                              " Use --unchanged to commit anyhow.")
3439
3164
        except ConflictsInTree:
3440
 
            raise errors.BzrCommandError(gettext('Conflicts detected in working '
 
3165
            raise errors.BzrCommandError('Conflicts detected in working '
3441
3166
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3442
 
                ' resolve.'))
 
3167
                ' resolve.')
3443
3168
        except StrictCommitFailed:
3444
 
            raise errors.BzrCommandError(gettext("Commit refused because there are"
3445
 
                              " unknown files in the working tree."))
 
3169
            raise errors.BzrCommandError("Commit refused because there are"
 
3170
                              " unknown files in the working tree.")
3446
3171
        except errors.BoundBranchOutOfDate, e:
3447
 
            e.extra_help = (gettext("\n"
3448
 
                'To commit to master branch, run update and then commit.\n'
3449
 
                'You can also pass --local to commit to continue working '
3450
 
                'disconnected.'))
3451
 
            raise
 
3172
            raise errors.BzrCommandError(str(e) + "\n"
 
3173
            'To commit to master branch, run update and then commit.\n'
 
3174
            'You can also pass --local to commit to continue working '
 
3175
            'disconnected.')
3452
3176
 
3453
3177
 
3454
3178
class cmd_check(Command):
3455
 
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3179
    """Validate working tree structure, branch consistency and repository history.
3456
3180
 
3457
3181
    This command checks various invariants about branch and repository storage
3458
3182
    to detect data corruption or bzr bugs.
3522
3246
 
3523
3247
 
3524
3248
class cmd_upgrade(Command):
3525
 
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
3526
 
 
3527
 
    When the default format has changed after a major new release of
3528
 
    Bazaar, you may be informed during certain operations that you
3529
 
    should upgrade. Upgrading to a newer format may improve performance
3530
 
    or make new features available. It may however limit interoperability
3531
 
    with older repositories or with older versions of Bazaar.
3532
 
 
3533
 
    If you wish to upgrade to a particular format rather than the
3534
 
    current default, that can be specified using the --format option.
3535
 
    As a consequence, you can use the upgrade command this way to
3536
 
    "downgrade" to an earlier format, though some conversions are
3537
 
    a one way process (e.g. changing from the 1.x default to the
3538
 
    2.x default) so downgrading is not always possible.
3539
 
 
3540
 
    A backup.bzr.~#~ directory is created at the start of the conversion
3541
 
    process (where # is a number). By default, this is left there on
3542
 
    completion. If the conversion fails, delete the new .bzr directory
3543
 
    and rename this one back in its place. Use the --clean option to ask
3544
 
    for the backup.bzr directory to be removed on successful conversion.
3545
 
    Alternatively, you can delete it by hand if everything looks good
3546
 
    afterwards.
3547
 
 
3548
 
    If the location given is a shared repository, dependent branches
3549
 
    are also converted provided the repository converts successfully.
3550
 
    If the conversion of a branch fails, remaining branches are still
3551
 
    tried.
3552
 
 
3553
 
    For more information on upgrades, see the Bazaar Upgrade Guide,
3554
 
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
 
3249
    """Upgrade branch storage to current format.
 
3250
 
 
3251
    The check command or bzr developers may sometimes advise you to run
 
3252
    this command. When the default format has changed you may also be warned
 
3253
    during other operations to upgrade.
3555
3254
    """
3556
3255
 
3557
 
    _see_also = ['check', 'reconcile', 'formats']
 
3256
    _see_also = ['check']
3558
3257
    takes_args = ['url?']
3559
3258
    takes_options = [
3560
 
        RegistryOption('format',
3561
 
            help='Upgrade to a specific format.  See "bzr help'
3562
 
                 ' formats" for details.',
3563
 
            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3564
 
            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3565
 
            value_switches=True, title='Branch format'),
3566
 
        Option('clean',
3567
 
            help='Remove the backup.bzr directory if successful.'),
3568
 
        Option('dry-run',
3569
 
            help="Show what would be done, but don't actually do anything."),
3570
 
    ]
 
3259
                    RegistryOption('format',
 
3260
                        help='Upgrade to a specific format.  See "bzr help'
 
3261
                             ' formats" for details.',
 
3262
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3263
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
 
3264
                        value_switches=True, title='Branch format'),
 
3265
                    ]
3571
3266
 
3572
 
    def run(self, url='.', format=None, clean=False, dry_run=False):
 
3267
    def run(self, url='.', format=None):
3573
3268
        from bzrlib.upgrade import upgrade
3574
 
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3575
 
        if exceptions:
3576
 
            if len(exceptions) == 1:
3577
 
                # Compatibility with historical behavior
3578
 
                raise exceptions[0]
3579
 
            else:
3580
 
                return 3
 
3269
        upgrade(url, format)
3581
3270
 
3582
3271
 
3583
3272
class cmd_whoami(Command):
3584
 
    __doc__ = """Show or set bzr user id.
 
3273
    """Show or set bzr user id.
3585
3274
 
3586
3275
    :Examples:
3587
3276
        Show the email of the current user::
3592
3281
 
3593
3282
            bzr whoami "Frank Chu <fchu@example.com>"
3594
3283
    """
3595
 
    takes_options = [ 'directory',
3596
 
                      Option('email',
 
3284
    takes_options = [ Option('email',
3597
3285
                             help='Display email address only.'),
3598
3286
                      Option('branch',
3599
3287
                             help='Set identity for the current branch instead of '
3603
3291
    encoding_type = 'replace'
3604
3292
 
3605
3293
    @display_command
3606
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
3294
    def run(self, email=False, branch=False, name=None):
3607
3295
        if name is None:
3608
 
            if directory is None:
3609
 
                # use branch if we're inside one; otherwise global config
3610
 
                try:
3611
 
                    c = Branch.open_containing(u'.')[0].get_config()
3612
 
                except errors.NotBranchError:
3613
 
                    c = _mod_config.GlobalConfig()
3614
 
            else:
3615
 
                c = Branch.open(directory).get_config()
 
3296
            # use branch if we're inside one; otherwise global config
 
3297
            try:
 
3298
                c = Branch.open_containing('.')[0].get_config()
 
3299
            except errors.NotBranchError:
 
3300
                c = config.GlobalConfig()
3616
3301
            if email:
3617
3302
                self.outf.write(c.user_email() + '\n')
3618
3303
            else:
3619
3304
                self.outf.write(c.username() + '\n')
3620
3305
            return
3621
3306
 
3622
 
        if email:
3623
 
            raise errors.BzrCommandError(gettext("--email can only be used to display existing "
3624
 
                                         "identity"))
3625
 
 
3626
3307
        # display a warning if an email address isn't included in the given name.
3627
3308
        try:
3628
 
            _mod_config.extract_email_address(name)
 
3309
            config.extract_email_address(name)
3629
3310
        except errors.NoEmailInUsername, e:
3630
3311
            warning('"%s" does not seem to contain an email address.  '
3631
3312
                    'This is allowed, but not recommended.', name)
3632
3313
 
3633
3314
        # use global config unless --branch given
3634
3315
        if branch:
3635
 
            if directory is None:
3636
 
                c = Branch.open_containing(u'.')[0].get_config()
3637
 
            else:
3638
 
                c = Branch.open(directory).get_config()
 
3316
            c = Branch.open_containing('.')[0].get_config()
3639
3317
        else:
3640
 
            c = _mod_config.GlobalConfig()
 
3318
            c = config.GlobalConfig()
3641
3319
        c.set_user_option('email', name)
3642
3320
 
3643
3321
 
3644
3322
class cmd_nick(Command):
3645
 
    __doc__ = """Print or set the branch nickname.
 
3323
    """Print or set the branch nickname.
3646
3324
 
3647
3325
    If unset, the tree root directory name is used as the nickname.
3648
3326
    To print the current nickname, execute with no argument.
3653
3331
 
3654
3332
    _see_also = ['info']
3655
3333
    takes_args = ['nickname?']
3656
 
    takes_options = ['directory']
3657
 
    def run(self, nickname=None, directory=u'.'):
3658
 
        branch = Branch.open_containing(directory)[0]
 
3334
    def run(self, nickname=None):
 
3335
        branch = Branch.open_containing(u'.')[0]
3659
3336
        if nickname is None:
3660
3337
            self.printme(branch)
3661
3338
        else:
3663
3340
 
3664
3341
    @display_command
3665
3342
    def printme(self, branch):
3666
 
        self.outf.write('%s\n' % branch.nick)
 
3343
        print branch.nick
3667
3344
 
3668
3345
 
3669
3346
class cmd_alias(Command):
3670
 
    __doc__ = """Set/unset and display aliases.
 
3347
    """Set/unset and display aliases.
3671
3348
 
3672
3349
    :Examples:
3673
3350
        Show the current aliases::
3706
3383
 
3707
3384
    def remove_alias(self, alias_name):
3708
3385
        if alias_name is None:
3709
 
            raise errors.BzrCommandError(gettext(
3710
 
                'bzr alias --remove expects an alias to remove.'))
 
3386
            raise errors.BzrCommandError(
 
3387
                'bzr alias --remove expects an alias to remove.')
3711
3388
        # If alias is not found, print something like:
3712
3389
        # unalias: foo: not found
3713
 
        c = _mod_config.GlobalConfig()
 
3390
        c = config.GlobalConfig()
3714
3391
        c.unset_alias(alias_name)
3715
3392
 
3716
3393
    @display_command
3717
3394
    def print_aliases(self):
3718
3395
        """Print out the defined aliases in a similar format to bash."""
3719
 
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3396
        aliases = config.GlobalConfig().get_aliases()
3720
3397
        for key, value in sorted(aliases.iteritems()):
3721
3398
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3722
3399
 
3732
3409
 
3733
3410
    def set_alias(self, alias_name, alias_command):
3734
3411
        """Save the alias in the global config."""
3735
 
        c = _mod_config.GlobalConfig()
 
3412
        c = config.GlobalConfig()
3736
3413
        c.set_alias(alias_name, alias_command)
3737
3414
 
3738
3415
 
3739
3416
class cmd_selftest(Command):
3740
 
    __doc__ = """Run internal test suite.
 
3417
    """Run internal test suite.
3741
3418
 
3742
3419
    If arguments are given, they are regular expressions that say which tests
3743
3420
    should run.  Tests matching any expression are run, and other tests are
3773
3450
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3774
3451
    into a pdb postmortem session.
3775
3452
 
3776
 
    The --coverage=DIRNAME global option produces a report with covered code
3777
 
    indicated.
3778
 
 
3779
3453
    :Examples:
3780
3454
        Run only tests relating to 'ignore'::
3781
3455
 
3790
3464
    def get_transport_type(typestring):
3791
3465
        """Parse and return a transport specifier."""
3792
3466
        if typestring == "sftp":
3793
 
            from bzrlib.tests import stub_sftp
3794
 
            return stub_sftp.SFTPAbsoluteServer
3795
 
        elif typestring == "memory":
3796
 
            from bzrlib.tests import test_server
3797
 
            return memory.MemoryServer
3798
 
        elif typestring == "fakenfs":
3799
 
            from bzrlib.tests import test_server
3800
 
            return test_server.FakeNFSServer
 
3467
            from bzrlib.transport.sftp import SFTPAbsoluteServer
 
3468
            return SFTPAbsoluteServer
 
3469
        if typestring == "memory":
 
3470
            from bzrlib.transport.memory import MemoryServer
 
3471
            return MemoryServer
 
3472
        if typestring == "fakenfs":
 
3473
            from bzrlib.transport.fakenfs import FakeNFSServer
 
3474
            return FakeNFSServer
3801
3475
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3802
3476
            (typestring)
3803
3477
        raise errors.BzrCommandError(msg)
3814
3488
                                 'throughout the test suite.',
3815
3489
                            type=get_transport_type),
3816
3490
                     Option('benchmark',
3817
 
                            help='Run the benchmarks rather than selftests.',
3818
 
                            hidden=True),
 
3491
                            help='Run the benchmarks rather than selftests.'),
3819
3492
                     Option('lsprof-timed',
3820
3493
                            help='Generate lsprof output for benchmarked'
3821
3494
                                 ' sections of code.'),
3822
3495
                     Option('lsprof-tests',
3823
3496
                            help='Generate lsprof output for each test.'),
 
3497
                     Option('cache-dir', type=str,
 
3498
                            help='Cache intermediate benchmark output in this '
 
3499
                                 'directory.'),
3824
3500
                     Option('first',
3825
3501
                            help='Run all tests, but run specified tests first.',
3826
3502
                            short_name='f',
3835
3511
                     Option('randomize', type=str, argname="SEED",
3836
3512
                            help='Randomize the order of tests using the given'
3837
3513
                                 ' seed or "now" for the current time.'),
3838
 
                     ListOption('exclude', type=str, argname="PATTERN",
3839
 
                                short_name='x',
3840
 
                                help='Exclude tests that match this regular'
3841
 
                                ' expression.'),
 
3514
                     Option('exclude', type=str, argname="PATTERN",
 
3515
                            short_name='x',
 
3516
                            help='Exclude tests that match this regular'
 
3517
                                 ' expression.'),
3842
3518
                     Option('subunit',
3843
3519
                        help='Output test progress via subunit.'),
3844
3520
                     Option('strict', help='Fail on missing dependencies or '
3851
3527
                                param_name='starting_with', short_name='s',
3852
3528
                                help=
3853
3529
                                'Load only the tests starting with TESTID.'),
3854
 
                     Option('sync',
3855
 
                            help="By default we disable fsync and fdatasync"
3856
 
                                 " while running the test suite.")
3857
3530
                     ]
3858
3531
    encoding_type = 'replace'
3859
3532
 
3863
3536
 
3864
3537
    def run(self, testspecs_list=None, verbose=False, one=False,
3865
3538
            transport=None, benchmark=None,
3866
 
            lsprof_timed=None,
 
3539
            lsprof_timed=None, cache_dir=None,
3867
3540
            first=False, list_only=False,
3868
3541
            randomize=None, exclude=None, strict=False,
3869
3542
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3870
 
            parallel=None, lsprof_tests=False,
3871
 
            sync=False):
3872
 
        from bzrlib import tests
3873
 
 
 
3543
            parallel=None, lsprof_tests=False):
 
3544
        from bzrlib.tests import selftest
 
3545
        import bzrlib.benchmarks as benchmarks
 
3546
        from bzrlib.benchmarks import tree_creator
 
3547
 
 
3548
        # Make deprecation warnings visible, unless -Werror is set
 
3549
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3550
 
 
3551
        if cache_dir is not None:
 
3552
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3874
3553
        if testspecs_list is not None:
3875
3554
            pattern = '|'.join(testspecs_list)
3876
3555
        else:
3879
3558
            try:
3880
3559
                from bzrlib.tests import SubUnitBzrRunner
3881
3560
            except ImportError:
3882
 
                raise errors.BzrCommandError(gettext("subunit not available. subunit "
3883
 
                    "needs to be installed to use --subunit."))
 
3561
                raise errors.BzrCommandError("subunit not available. subunit "
 
3562
                    "needs to be installed to use --subunit.")
3884
3563
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3885
 
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3886
 
            # stdout, which would corrupt the subunit stream. 
3887
 
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3888
 
            # following code can be deleted when it's sufficiently deployed
3889
 
            # -- vila/mgz 20100514
3890
 
            if (sys.platform == "win32"
3891
 
                and getattr(sys.stdout, 'fileno', None) is not None):
3892
 
                import msvcrt
3893
 
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3894
3564
        if parallel:
3895
3565
            self.additional_selftest_args.setdefault(
3896
3566
                'suite_decorators', []).append(parallel)
3897
3567
        if benchmark:
3898
 
            raise errors.BzrCommandError(gettext(
3899
 
                "--benchmark is no longer supported from bzr 2.2; "
3900
 
                "use bzr-usertest instead"))
3901
 
        test_suite_factory = None
3902
 
        if not exclude:
3903
 
            exclude_pattern = None
 
3568
            test_suite_factory = benchmarks.test_suite
 
3569
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3570
            verbose = not is_quiet()
 
3571
            # TODO: should possibly lock the history file...
 
3572
            benchfile = open(".perf_history", "at", buffering=1)
3904
3573
        else:
3905
 
            exclude_pattern = '(' + '|'.join(exclude) + ')'
3906
 
        if not sync:
3907
 
            self._disable_fsync()
3908
 
        selftest_kwargs = {"verbose": verbose,
3909
 
                          "pattern": pattern,
3910
 
                          "stop_on_failure": one,
3911
 
                          "transport": transport,
3912
 
                          "test_suite_factory": test_suite_factory,
3913
 
                          "lsprof_timed": lsprof_timed,
3914
 
                          "lsprof_tests": lsprof_tests,
3915
 
                          "matching_tests_first": first,
3916
 
                          "list_only": list_only,
3917
 
                          "random_seed": randomize,
3918
 
                          "exclude_pattern": exclude_pattern,
3919
 
                          "strict": strict,
3920
 
                          "load_list": load_list,
3921
 
                          "debug_flags": debugflag,
3922
 
                          "starting_with": starting_with
3923
 
                          }
3924
 
        selftest_kwargs.update(self.additional_selftest_args)
3925
 
 
3926
 
        # Make deprecation warnings visible, unless -Werror is set
3927
 
        cleanup = symbol_versioning.activate_deprecation_warnings(
3928
 
            override=False)
 
3574
            test_suite_factory = None
 
3575
            benchfile = None
3929
3576
        try:
3930
 
            result = tests.selftest(**selftest_kwargs)
 
3577
            selftest_kwargs = {"verbose": verbose,
 
3578
                              "pattern": pattern,
 
3579
                              "stop_on_failure": one,
 
3580
                              "transport": transport,
 
3581
                              "test_suite_factory": test_suite_factory,
 
3582
                              "lsprof_timed": lsprof_timed,
 
3583
                              "lsprof_tests": lsprof_tests,
 
3584
                              "bench_history": benchfile,
 
3585
                              "matching_tests_first": first,
 
3586
                              "list_only": list_only,
 
3587
                              "random_seed": randomize,
 
3588
                              "exclude_pattern": exclude,
 
3589
                              "strict": strict,
 
3590
                              "load_list": load_list,
 
3591
                              "debug_flags": debugflag,
 
3592
                              "starting_with": starting_with
 
3593
                              }
 
3594
            selftest_kwargs.update(self.additional_selftest_args)
 
3595
            result = selftest(**selftest_kwargs)
3931
3596
        finally:
3932
 
            cleanup()
 
3597
            if benchfile is not None:
 
3598
                benchfile.close()
3933
3599
        return int(not result)
3934
3600
 
3935
 
    def _disable_fsync(self):
3936
 
        """Change the 'os' functionality to not synchronize."""
3937
 
        self._orig_fsync = getattr(os, 'fsync', None)
3938
 
        if self._orig_fsync is not None:
3939
 
            os.fsync = lambda filedes: None
3940
 
        self._orig_fdatasync = getattr(os, 'fdatasync', None)
3941
 
        if self._orig_fdatasync is not None:
3942
 
            os.fdatasync = lambda filedes: None
3943
 
 
3944
3601
 
3945
3602
class cmd_version(Command):
3946
 
    __doc__ = """Show version of bzr."""
 
3603
    """Show version of bzr."""
3947
3604
 
3948
3605
    encoding_type = 'replace'
3949
3606
    takes_options = [
3960
3617
 
3961
3618
 
3962
3619
class cmd_rocks(Command):
3963
 
    __doc__ = """Statement of optimism."""
 
3620
    """Statement of optimism."""
3964
3621
 
3965
3622
    hidden = True
3966
3623
 
3967
3624
    @display_command
3968
3625
    def run(self):
3969
 
        self.outf.write(gettext("It sure does!\n"))
 
3626
        print "It sure does!"
3970
3627
 
3971
3628
 
3972
3629
class cmd_find_merge_base(Command):
3973
 
    __doc__ = """Find and print a base revision for merging two branches."""
 
3630
    """Find and print a base revision for merging two branches."""
3974
3631
    # TODO: Options to specify revisions on either side, as if
3975
3632
    #       merging only part of the history.
3976
3633
    takes_args = ['branch', 'other']
3982
3639
 
3983
3640
        branch1 = Branch.open_containing(branch)[0]
3984
3641
        branch2 = Branch.open_containing(other)[0]
3985
 
        self.add_cleanup(branch1.lock_read().unlock)
3986
 
        self.add_cleanup(branch2.lock_read().unlock)
3987
 
        last1 = ensure_null(branch1.last_revision())
3988
 
        last2 = ensure_null(branch2.last_revision())
3989
 
 
3990
 
        graph = branch1.repository.get_graph(branch2.repository)
3991
 
        base_rev_id = graph.find_unique_lca(last1, last2)
3992
 
 
3993
 
        self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
 
3642
        branch1.lock_read()
 
3643
        try:
 
3644
            branch2.lock_read()
 
3645
            try:
 
3646
                last1 = ensure_null(branch1.last_revision())
 
3647
                last2 = ensure_null(branch2.last_revision())
 
3648
 
 
3649
                graph = branch1.repository.get_graph(branch2.repository)
 
3650
                base_rev_id = graph.find_unique_lca(last1, last2)
 
3651
 
 
3652
                print 'merge base is revision %s' % base_rev_id
 
3653
            finally:
 
3654
                branch2.unlock()
 
3655
        finally:
 
3656
            branch1.unlock()
3994
3657
 
3995
3658
 
3996
3659
class cmd_merge(Command):
3997
 
    __doc__ = """Perform a three-way merge.
 
3660
    """Perform a three-way merge.
3998
3661
 
3999
3662
    The source of the merge can be specified either in the form of a branch,
4000
3663
    or in the form of a path to a file containing a merge directive generated
4001
3664
    with bzr send. If neither is specified, the default is the upstream branch
4002
 
    or the branch most recently merged using --remember.  The source of the
4003
 
    merge may also be specified in the form of a path to a file in another
4004
 
    branch:  in this case, only the modifications to that file are merged into
4005
 
    the current working tree.
4006
 
 
4007
 
    When merging from a branch, by default bzr will try to merge in all new
4008
 
    work from the other branch, automatically determining an appropriate base
4009
 
    revision.  If this fails, you may need to give an explicit base.
4010
 
 
4011
 
    To pick a different ending revision, pass "--revision OTHER".  bzr will
4012
 
    try to merge in all new work up to and including revision OTHER.
4013
 
 
4014
 
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
4015
 
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
4016
 
    causes some revisions to be skipped, i.e. if the destination branch does
4017
 
    not already contain revision BASE, such a merge is commonly referred to as
4018
 
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4019
 
    cherrypicks. The changes look like a normal commit, and the history of the
4020
 
    changes from the other branch is not stored in the commit.
4021
 
 
4022
 
    Revision numbers are always relative to the source branch.
 
3665
    or the branch most recently merged using --remember.
 
3666
 
 
3667
    When merging a branch, by default the tip will be merged. To pick a different
 
3668
    revision, pass --revision. If you specify two values, the first will be used as
 
3669
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
3670
    available revisions, like this is commonly referred to as "cherrypicking".
 
3671
 
 
3672
    Revision numbers are always relative to the branch being merged.
 
3673
 
 
3674
    By default, bzr will try to merge in all new work from the other
 
3675
    branch, automatically determining an appropriate base.  If this
 
3676
    fails, you may need to give an explicit base.
4023
3677
 
4024
3678
    Merge will do its best to combine the changes in two branches, but there
4025
3679
    are some kinds of problems only a human can fix.  When it encounters those,
4028
3682
 
4029
3683
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
4030
3684
 
4031
 
    If there is no default branch set, the first merge will set it (use
4032
 
    --no-remember to avoid setting it). After that, you can omit the branch
4033
 
    to use the default.  To change the default, use --remember. The value will
4034
 
    only be saved if the remote location can be accessed.
 
3685
    If there is no default branch set, the first merge will set it. After
 
3686
    that, you can omit the branch to use the default.  To change the
 
3687
    default, use --remember. The value will only be saved if the remote
 
3688
    location can be accessed.
4035
3689
 
4036
3690
    The results of the merge are placed into the destination working
4037
3691
    directory, where they can be reviewed (with bzr diff), tested, and then
4038
3692
    committed to record the result of the merge.
4039
3693
 
4040
3694
    merge refuses to run if there are any uncommitted changes, unless
4041
 
    --force is given.  If --force is given, then the changes from the source 
4042
 
    will be merged with the current working tree, including any uncommitted
4043
 
    changes in the tree.  The --force option can also be used to create a
4044
 
    merge revision which has more than two parents.
4045
 
 
4046
 
    If one would like to merge changes from the working tree of the other
4047
 
    branch without merging any committed revisions, the --uncommitted option
4048
 
    can be given.
 
3695
    --force is given.
4049
3696
 
4050
3697
    To select only some changes to merge, use "merge -i", which will prompt
4051
3698
    you to apply each diff hunk and file change, similar to "shelve".
4052
3699
 
4053
3700
    :Examples:
4054
 
        To merge all new revisions from bzr.dev::
 
3701
        To merge the latest revision from bzr.dev::
4055
3702
 
4056
3703
            bzr merge ../bzr.dev
4057
3704
 
4066
3713
        To apply a merge directive contained in /tmp/merge::
4067
3714
 
4068
3715
            bzr merge /tmp/merge
4069
 
 
4070
 
        To create a merge revision with three parents from two branches
4071
 
        feature1a and feature1b:
4072
 
 
4073
 
            bzr merge ../feature1a
4074
 
            bzr merge ../feature1b --force
4075
 
            bzr commit -m 'revision with three parents'
4076
3716
    """
4077
3717
 
4078
3718
    encoding_type = 'exact'
4094
3734
                ' completely merged into the source, pull from the'
4095
3735
                ' source rather than merging.  When this happens,'
4096
3736
                ' you do not need to commit the result.'),
4097
 
        custom_help('directory',
 
3737
        Option('directory',
4098
3738
               help='Branch to merge into, '
4099
 
                    'rather than the one containing the working directory.'),
 
3739
                    'rather than the one containing the working directory.',
 
3740
               short_name='d',
 
3741
               type=unicode,
 
3742
               ),
4100
3743
        Option('preview', help='Instead of merging, show a diff of the'
4101
3744
               ' merge.'),
4102
3745
        Option('interactive', help='Select changes interactively.',
4104
3747
    ]
4105
3748
 
4106
3749
    def run(self, location=None, revision=None, force=False,
4107
 
            merge_type=None, show_base=False, reprocess=None, remember=None,
 
3750
            merge_type=None, show_base=False, reprocess=None, remember=False,
4108
3751
            uncommitted=False, pull=False,
4109
3752
            directory=None,
4110
3753
            preview=False,
4118
3761
        merger = None
4119
3762
        allow_pending = True
4120
3763
        verified = 'inapplicable'
4121
 
 
4122
3764
        tree = WorkingTree.open_containing(directory)[0]
4123
 
        if tree.branch.revno() == 0:
4124
 
            raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
4125
 
                                         'https://bugs.launchpad.net/bzr/+bug/308562'))
4126
3765
 
4127
3766
        try:
4128
3767
            basis_tree = tree.revision_tree(tree.last_revision())
4137
3776
        view_info = _get_view_info_for_change_reporter(tree)
4138
3777
        change_reporter = delta._ChangeReporter(
4139
3778
            unversioned_filter=tree.is_ignored, view_info=view_info)
4140
 
        pb = ui.ui_factory.nested_progress_bar()
4141
 
        self.add_cleanup(pb.finished)
4142
 
        self.add_cleanup(tree.lock_write().unlock)
4143
 
        if location is not None:
4144
 
            try:
4145
 
                mergeable = bundle.read_mergeable_from_url(location,
4146
 
                    possible_transports=possible_transports)
4147
 
            except errors.NotABundle:
4148
 
                mergeable = None
 
3779
        cleanups = []
 
3780
        try:
 
3781
            pb = ui.ui_factory.nested_progress_bar()
 
3782
            cleanups.append(pb.finished)
 
3783
            tree.lock_write()
 
3784
            cleanups.append(tree.unlock)
 
3785
            if location is not None:
 
3786
                try:
 
3787
                    mergeable = bundle.read_mergeable_from_url(location,
 
3788
                        possible_transports=possible_transports)
 
3789
                except errors.NotABundle:
 
3790
                    mergeable = None
 
3791
                else:
 
3792
                    if uncommitted:
 
3793
                        raise errors.BzrCommandError('Cannot use --uncommitted'
 
3794
                            ' with bundles or merge directives.')
 
3795
 
 
3796
                    if revision is not None:
 
3797
                        raise errors.BzrCommandError(
 
3798
                            'Cannot use -r with merge directives or bundles')
 
3799
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
3800
                       mergeable, pb)
 
3801
 
 
3802
            if merger is None and uncommitted:
 
3803
                if revision is not None and len(revision) > 0:
 
3804
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
 
3805
                        ' --revision at the same time.')
 
3806
                merger = self.get_merger_from_uncommitted(tree, location, pb,
 
3807
                                                          cleanups)
 
3808
                allow_pending = False
 
3809
 
 
3810
            if merger is None:
 
3811
                merger, allow_pending = self._get_merger_from_branch(tree,
 
3812
                    location, revision, remember, possible_transports, pb)
 
3813
 
 
3814
            merger.merge_type = merge_type
 
3815
            merger.reprocess = reprocess
 
3816
            merger.show_base = show_base
 
3817
            self.sanity_check_merger(merger)
 
3818
            if (merger.base_rev_id == merger.other_rev_id and
 
3819
                merger.other_rev_id is not None):
 
3820
                note('Nothing to do.')
 
3821
                return 0
 
3822
            if pull:
 
3823
                if merger.interesting_files is not None:
 
3824
                    raise errors.BzrCommandError('Cannot pull individual files')
 
3825
                if (merger.base_rev_id == tree.last_revision()):
 
3826
                    result = tree.pull(merger.other_branch, False,
 
3827
                                       merger.other_rev_id)
 
3828
                    result.report(self.outf)
 
3829
                    return 0
 
3830
            if merger.this_basis is None:
 
3831
                raise errors.BzrCommandError(
 
3832
                    "This branch has no commits."
 
3833
                    " (perhaps you would prefer 'bzr pull')")
 
3834
            if preview:
 
3835
                return self._do_preview(merger, cleanups)
 
3836
            elif interactive:
 
3837
                return self._do_interactive(merger, cleanups)
4149
3838
            else:
4150
 
                if uncommitted:
4151
 
                    raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4152
 
                        ' with bundles or merge directives.'))
4153
 
 
4154
 
                if revision is not None:
4155
 
                    raise errors.BzrCommandError(gettext(
4156
 
                        'Cannot use -r with merge directives or bundles'))
4157
 
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
4158
 
                   mergeable, None)
4159
 
 
4160
 
        if merger is None and uncommitted:
4161
 
            if revision is not None and len(revision) > 0:
4162
 
                raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4163
 
                    ' --revision at the same time.'))
4164
 
            merger = self.get_merger_from_uncommitted(tree, location, None)
4165
 
            allow_pending = False
4166
 
 
4167
 
        if merger is None:
4168
 
            merger, allow_pending = self._get_merger_from_branch(tree,
4169
 
                location, revision, remember, possible_transports, None)
4170
 
 
4171
 
        merger.merge_type = merge_type
4172
 
        merger.reprocess = reprocess
4173
 
        merger.show_base = show_base
4174
 
        self.sanity_check_merger(merger)
4175
 
        if (merger.base_rev_id == merger.other_rev_id and
4176
 
            merger.other_rev_id is not None):
4177
 
            # check if location is a nonexistent file (and not a branch) to
4178
 
            # disambiguate the 'Nothing to do'
4179
 
            if merger.interesting_files:
4180
 
                if not merger.other_tree.has_filename(
4181
 
                    merger.interesting_files[0]):
4182
 
                    note(gettext("merger: ") + str(merger))
4183
 
                    raise errors.PathsDoNotExist([location])
4184
 
            note(gettext('Nothing to do.'))
4185
 
            return 0
4186
 
        if pull and not preview:
4187
 
            if merger.interesting_files is not None:
4188
 
                raise errors.BzrCommandError(gettext('Cannot pull individual files'))
4189
 
            if (merger.base_rev_id == tree.last_revision()):
4190
 
                result = tree.pull(merger.other_branch, False,
4191
 
                                   merger.other_rev_id)
4192
 
                result.report(self.outf)
4193
 
                return 0
4194
 
        if merger.this_basis is None:
4195
 
            raise errors.BzrCommandError(gettext(
4196
 
                "This branch has no commits."
4197
 
                " (perhaps you would prefer 'bzr pull')"))
4198
 
        if preview:
4199
 
            return self._do_preview(merger)
4200
 
        elif interactive:
4201
 
            return self._do_interactive(merger)
4202
 
        else:
4203
 
            return self._do_merge(merger, change_reporter, allow_pending,
4204
 
                                  verified)
4205
 
 
4206
 
    def _get_preview(self, merger):
 
3839
                return self._do_merge(merger, change_reporter, allow_pending,
 
3840
                                      verified)
 
3841
        finally:
 
3842
            for cleanup in reversed(cleanups):
 
3843
                cleanup()
 
3844
 
 
3845
    def _get_preview(self, merger, cleanups):
4207
3846
        tree_merger = merger.make_merger()
4208
3847
        tt = tree_merger.make_preview_transform()
4209
 
        self.add_cleanup(tt.finalize)
 
3848
        cleanups.append(tt.finalize)
4210
3849
        result_tree = tt.get_preview_tree()
4211
3850
        return result_tree
4212
3851
 
4213
 
    def _do_preview(self, merger):
 
3852
    def _do_preview(self, merger, cleanups):
4214
3853
        from bzrlib.diff import show_diff_trees
4215
 
        result_tree = self._get_preview(merger)
4216
 
        path_encoding = osutils.get_diff_header_encoding()
 
3854
        result_tree = self._get_preview(merger, cleanups)
4217
3855
        show_diff_trees(merger.this_tree, result_tree, self.outf,
4218
 
                        old_label='', new_label='',
4219
 
                        path_encoding=path_encoding)
 
3856
                        old_label='', new_label='')
4220
3857
 
4221
3858
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
4222
3859
        merger.change_reporter = change_reporter
4230
3867
        else:
4231
3868
            return 0
4232
3869
 
4233
 
    def _do_interactive(self, merger):
 
3870
    def _do_interactive(self, merger, cleanups):
4234
3871
        """Perform an interactive merge.
4235
3872
 
4236
3873
        This works by generating a preview tree of the merge, then using
4238
3875
        and the preview tree.
4239
3876
        """
4240
3877
        from bzrlib import shelf_ui
4241
 
        result_tree = self._get_preview(merger)
 
3878
        result_tree = self._get_preview(merger, cleanups)
4242
3879
        writer = bzrlib.option.diff_writer_registry.get()
4243
3880
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
4244
3881
                                   reporter=shelf_ui.ApplyReporter(),
4251
3888
    def sanity_check_merger(self, merger):
4252
3889
        if (merger.show_base and
4253
3890
            not merger.merge_type is _mod_merge.Merge3Merger):
4254
 
            raise errors.BzrCommandError(gettext("Show-base is not supported for this"
4255
 
                                         " merge type. %s") % merger.merge_type)
 
3891
            raise errors.BzrCommandError("Show-base is not supported for this"
 
3892
                                         " merge type. %s" % merger.merge_type)
4256
3893
        if merger.reprocess is None:
4257
3894
            if merger.show_base:
4258
3895
                merger.reprocess = False
4260
3897
                # Use reprocess if the merger supports it
4261
3898
                merger.reprocess = merger.merge_type.supports_reprocess
4262
3899
        if merger.reprocess and not merger.merge_type.supports_reprocess:
4263
 
            raise errors.BzrCommandError(gettext("Conflict reduction is not supported"
4264
 
                                         " for merge type %s.") %
 
3900
            raise errors.BzrCommandError("Conflict reduction is not supported"
 
3901
                                         " for merge type %s." %
4265
3902
                                         merger.merge_type)
4266
3903
        if merger.reprocess and merger.show_base:
4267
 
            raise errors.BzrCommandError(gettext("Cannot do conflict reduction and"
4268
 
                                         " show base."))
 
3904
            raise errors.BzrCommandError("Cannot do conflict reduction and"
 
3905
                                         " show base.")
4269
3906
 
4270
3907
    def _get_merger_from_branch(self, tree, location, revision, remember,
4271
3908
                                possible_transports, pb):
4298
3935
        if other_revision_id is None:
4299
3936
            other_revision_id = _mod_revision.ensure_null(
4300
3937
                other_branch.last_revision())
4301
 
        # Remember where we merge from. We need to remember if:
4302
 
        # - user specify a location (and we don't merge from the parent
4303
 
        #   branch)
4304
 
        # - user ask to remember or there is no previous location set to merge
4305
 
        #   from and user didn't ask to *not* remember
4306
 
        if (user_location is not None
4307
 
            and ((remember
4308
 
                  or (remember is None
4309
 
                      and tree.branch.get_submit_branch() is None)))):
 
3938
        # Remember where we merge from
 
3939
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3940
             user_location is not None):
4310
3941
            tree.branch.set_submit_branch(other_branch.base)
4311
 
        # Merge tags (but don't set them in the master branch yet, the user
4312
 
        # might revert this merge).  Commit will propagate them.
4313
 
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
 
3942
        _merge_tags_if_possible(other_branch, tree.branch)
4314
3943
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4315
3944
            other_revision_id, base_revision_id, other_branch, base_branch)
4316
3945
        if other_path != '':
4320
3949
            allow_pending = True
4321
3950
        return merger, allow_pending
4322
3951
 
4323
 
    def get_merger_from_uncommitted(self, tree, location, pb):
 
3952
    def get_merger_from_uncommitted(self, tree, location, pb, cleanups):
4324
3953
        """Get a merger for uncommitted changes.
4325
3954
 
4326
3955
        :param tree: The tree the merger should apply to.
4327
3956
        :param location: The location containing uncommitted changes.
4328
3957
        :param pb: The progress bar to use for showing progress.
 
3958
        :param cleanups: A list of operations to perform to clean up the
 
3959
            temporary directories, unfinalized objects, etc.
4329
3960
        """
4330
3961
        location = self._select_branch_location(tree, location)[0]
4331
3962
        other_tree, other_path = WorkingTree.open_containing(location)
4375
4006
            stored_location_type = "parent"
4376
4007
        mutter("%s", stored_location)
4377
4008
        if stored_location is None:
4378
 
            raise errors.BzrCommandError(gettext("No location specified or remembered"))
 
4009
            raise errors.BzrCommandError("No location specified or remembered")
4379
4010
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
4380
 
        note(gettext("{0} remembered {1} location {2}").format(verb_string,
4381
 
                stored_location_type, display_url))
 
4011
        note(u"%s remembered %s location %s", verb_string,
 
4012
                stored_location_type, display_url)
4382
4013
        return stored_location
4383
4014
 
4384
4015
 
4385
4016
class cmd_remerge(Command):
4386
 
    __doc__ = """Redo a merge.
 
4017
    """Redo a merge.
4387
4018
 
4388
4019
    Use this if you want to try a different merge technique while resolving
4389
4020
    conflicts.  Some merge techniques are better than others, and remerge
4414
4045
 
4415
4046
    def run(self, file_list=None, merge_type=None, show_base=False,
4416
4047
            reprocess=False):
4417
 
        from bzrlib.conflicts import restore
4418
4048
        if merge_type is None:
4419
4049
            merge_type = _mod_merge.Merge3Merger
4420
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4421
 
        self.add_cleanup(tree.lock_write().unlock)
4422
 
        parents = tree.get_parent_ids()
4423
 
        if len(parents) != 2:
4424
 
            raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
4425
 
                                         " merges.  Not cherrypicking or"
4426
 
                                         " multi-merges."))
4427
 
        repository = tree.branch.repository
4428
 
        interesting_ids = None
4429
 
        new_conflicts = []
4430
 
        conflicts = tree.conflicts()
4431
 
        if file_list is not None:
4432
 
            interesting_ids = set()
4433
 
            for filename in file_list:
4434
 
                file_id = tree.path2id(filename)
4435
 
                if file_id is None:
4436
 
                    raise errors.NotVersionedError(filename)
4437
 
                interesting_ids.add(file_id)
4438
 
                if tree.kind(file_id) != "directory":
4439
 
                    continue
 
4050
        tree, file_list = tree_files(file_list)
 
4051
        tree.lock_write()
 
4052
        try:
 
4053
            parents = tree.get_parent_ids()
 
4054
            if len(parents) != 2:
 
4055
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
 
4056
                                             " merges.  Not cherrypicking or"
 
4057
                                             " multi-merges.")
 
4058
            repository = tree.branch.repository
 
4059
            interesting_ids = None
 
4060
            new_conflicts = []
 
4061
            conflicts = tree.conflicts()
 
4062
            if file_list is not None:
 
4063
                interesting_ids = set()
 
4064
                for filename in file_list:
 
4065
                    file_id = tree.path2id(filename)
 
4066
                    if file_id is None:
 
4067
                        raise errors.NotVersionedError(filename)
 
4068
                    interesting_ids.add(file_id)
 
4069
                    if tree.kind(file_id) != "directory":
 
4070
                        continue
4440
4071
 
4441
 
                for name, ie in tree.inventory.iter_entries(file_id):
4442
 
                    interesting_ids.add(ie.file_id)
4443
 
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4444
 
        else:
4445
 
            # Remerge only supports resolving contents conflicts
4446
 
            allowed_conflicts = ('text conflict', 'contents conflict')
4447
 
            restore_files = [c.path for c in conflicts
4448
 
                             if c.typestring in allowed_conflicts]
4449
 
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4450
 
        tree.set_conflicts(ConflictList(new_conflicts))
4451
 
        if file_list is not None:
4452
 
            restore_files = file_list
4453
 
        for filename in restore_files:
 
4072
                    for name, ie in tree.inventory.iter_entries(file_id):
 
4073
                        interesting_ids.add(ie.file_id)
 
4074
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
4075
            else:
 
4076
                # Remerge only supports resolving contents conflicts
 
4077
                allowed_conflicts = ('text conflict', 'contents conflict')
 
4078
                restore_files = [c.path for c in conflicts
 
4079
                                 if c.typestring in allowed_conflicts]
 
4080
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
 
4081
            tree.set_conflicts(ConflictList(new_conflicts))
 
4082
            if file_list is not None:
 
4083
                restore_files = file_list
 
4084
            for filename in restore_files:
 
4085
                try:
 
4086
                    restore(tree.abspath(filename))
 
4087
                except errors.NotConflicted:
 
4088
                    pass
 
4089
            # Disable pending merges, because the file texts we are remerging
 
4090
            # have not had those merges performed.  If we use the wrong parents
 
4091
            # list, we imply that the working tree text has seen and rejected
 
4092
            # all the changes from the other tree, when in fact those changes
 
4093
            # have not yet been seen.
 
4094
            pb = ui.ui_factory.nested_progress_bar()
 
4095
            tree.set_parent_ids(parents[:1])
4454
4096
            try:
4455
 
                restore(tree.abspath(filename))
4456
 
            except errors.NotConflicted:
4457
 
                pass
4458
 
        # Disable pending merges, because the file texts we are remerging
4459
 
        # have not had those merges performed.  If we use the wrong parents
4460
 
        # list, we imply that the working tree text has seen and rejected
4461
 
        # all the changes from the other tree, when in fact those changes
4462
 
        # have not yet been seen.
4463
 
        tree.set_parent_ids(parents[:1])
4464
 
        try:
4465
 
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4466
 
            merger.interesting_ids = interesting_ids
4467
 
            merger.merge_type = merge_type
4468
 
            merger.show_base = show_base
4469
 
            merger.reprocess = reprocess
4470
 
            conflicts = merger.do_merge()
 
4097
                merger = _mod_merge.Merger.from_revision_ids(pb,
 
4098
                                                             tree, parents[1])
 
4099
                merger.interesting_ids = interesting_ids
 
4100
                merger.merge_type = merge_type
 
4101
                merger.show_base = show_base
 
4102
                merger.reprocess = reprocess
 
4103
                conflicts = merger.do_merge()
 
4104
            finally:
 
4105
                tree.set_parent_ids(parents)
 
4106
                pb.finished()
4471
4107
        finally:
4472
 
            tree.set_parent_ids(parents)
 
4108
            tree.unlock()
4473
4109
        if conflicts > 0:
4474
4110
            return 1
4475
4111
        else:
4477
4113
 
4478
4114
 
4479
4115
class cmd_revert(Command):
4480
 
    __doc__ = """Revert files to a previous revision.
 
4116
    """Revert files to a previous revision.
4481
4117
 
4482
4118
    Giving a list of files will revert only those files.  Otherwise, all files
4483
4119
    will be reverted.  If the revision is not specified with '--revision', the
4484
4120
    last committed revision is used.
4485
4121
 
4486
4122
    To remove only some changes, without reverting to a prior version, use
4487
 
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
4488
 
    will remove the changes introduced by the second last commit (-2), without
4489
 
    affecting the changes introduced by the last commit (-1).  To remove
4490
 
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
4123
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
4124
    changes introduced by -2, without affecting the changes introduced by -1.
 
4125
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4491
4126
 
4492
4127
    By default, any files that have been manually changed will be backed up
4493
4128
    first.  (Files changed only by merge are not backed up.)  Backup files have
4503
4138
    created as above.  Directories containing unknown files will not be
4504
4139
    deleted.
4505
4140
 
4506
 
    The working tree contains a list of revisions that have been merged but
4507
 
    not yet committed. These revisions will be included as additional parents
4508
 
    of the next commit.  Normally, using revert clears that list as well as
4509
 
    reverting the files.  If any files are specified, revert leaves the list
4510
 
    of uncommitted merges alone and reverts only the files.  Use ``bzr revert
4511
 
    .`` in the tree root to revert all files but keep the recorded merges,
4512
 
    and ``bzr revert --forget-merges`` to clear the pending merge list without
 
4141
    The working tree contains a list of pending merged revisions, which will
 
4142
    be included as parents in the next commit.  Normally, revert clears that
 
4143
    list as well as reverting the files.  If any files are specified, revert
 
4144
    leaves the pending merge list alone and reverts only the files.  Use "bzr
 
4145
    revert ." in the tree root to revert all files but keep the merge record,
 
4146
    and "bzr revert --forget-merges" to clear the pending merge list without
4513
4147
    reverting any files.
4514
4148
 
4515
 
    Using "bzr revert --forget-merges", it is possible to apply all of the
4516
 
    changes from a branch in a single revision.  To do this, perform the merge
4517
 
    as desired.  Then doing revert with the "--forget-merges" option will keep
4518
 
    the content of the tree as it was, but it will clear the list of pending
4519
 
    merges.  The next commit will then contain all of the changes that are
4520
 
    present in the other branch, but without any other parent revisions.
4521
 
    Because this technique forgets where these changes originated, it may
4522
 
    cause additional conflicts on later merges involving the same source and
 
4149
    Using "bzr revert --forget-merges", it is possible to apply the changes
 
4150
    from an arbitrary merge as a single revision.  To do this, perform the
 
4151
    merge as desired.  Then doing revert with the "--forget-merges" option will
 
4152
    keep the content of the tree as it was, but it will clear the list of
 
4153
    pending merges.  The next commit will then contain all of the changes that
 
4154
    would have been in the merge, but without any mention of the other parent
 
4155
    revisions.  Because this technique forgets where these changes originated,
 
4156
    it may cause additional conflicts on later merges involving the source and
4523
4157
    target branches.
4524
4158
    """
4525
4159
 
4526
 
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4160
    _see_also = ['cat', 'export']
4527
4161
    takes_options = [
4528
4162
        'revision',
4529
4163
        Option('no-backup', "Do not save backups of reverted files."),
4534
4168
 
4535
4169
    def run(self, revision=None, no_backup=False, file_list=None,
4536
4170
            forget_merges=None):
4537
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4538
 
        self.add_cleanup(tree.lock_tree_write().unlock)
4539
 
        if forget_merges:
4540
 
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4541
 
        else:
4542
 
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4171
        tree, file_list = tree_files(file_list)
 
4172
        tree.lock_write()
 
4173
        try:
 
4174
            if forget_merges:
 
4175
                tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4176
            else:
 
4177
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4178
        finally:
 
4179
            tree.unlock()
4543
4180
 
4544
4181
    @staticmethod
4545
4182
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
4546
4183
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4547
 
        tree.revert(file_list, rev_tree, not no_backup, None,
4548
 
            report_changes=True)
 
4184
        pb = ui.ui_factory.nested_progress_bar()
 
4185
        try:
 
4186
            tree.revert(file_list, rev_tree, not no_backup, pb,
 
4187
                report_changes=True)
 
4188
        finally:
 
4189
            pb.finished()
4549
4190
 
4550
4191
 
4551
4192
class cmd_assert_fail(Command):
4552
 
    __doc__ = """Test reporting of assertion failures"""
 
4193
    """Test reporting of assertion failures"""
4553
4194
    # intended just for use in testing
4554
4195
 
4555
4196
    hidden = True
4559
4200
 
4560
4201
 
4561
4202
class cmd_help(Command):
4562
 
    __doc__ = """Show help on a command or other topic.
 
4203
    """Show help on a command or other topic.
4563
4204
    """
4564
4205
 
4565
4206
    _see_also = ['topics']
4578
4219
 
4579
4220
 
4580
4221
class cmd_shell_complete(Command):
4581
 
    __doc__ = """Show appropriate completions for context.
 
4222
    """Show appropriate completions for context.
4582
4223
 
4583
4224
    For a list of all available commands, say 'bzr shell-complete'.
4584
4225
    """
4593
4234
 
4594
4235
 
4595
4236
class cmd_missing(Command):
4596
 
    __doc__ = """Show unmerged/unpulled revisions between two branches.
 
4237
    """Show unmerged/unpulled revisions between two branches.
4597
4238
 
4598
4239
    OTHER_BRANCH may be local or remote.
4599
4240
 
4630
4271
    _see_also = ['merge', 'pull']
4631
4272
    takes_args = ['other_branch?']
4632
4273
    takes_options = [
4633
 
        'directory',
4634
4274
        Option('reverse', 'Reverse the order of revisions.'),
4635
4275
        Option('mine-only',
4636
4276
               'Display changes in the local branch only.'),
4648
4288
            type=_parse_revision_str,
4649
4289
            help='Filter on local branch revisions (inclusive). '
4650
4290
                'See "help revisionspec" for details.'),
4651
 
        Option('include-merged',
 
4291
        Option('include-merges',
4652
4292
               'Show all revisions in addition to the mainline ones.'),
4653
 
        Option('include-merges', hidden=True,
4654
 
               help='Historical alias for --include-merged.'),
4655
4293
        ]
4656
4294
    encoding_type = 'replace'
4657
4295
 
4660
4298
            theirs_only=False,
4661
4299
            log_format=None, long=False, short=False, line=False,
4662
4300
            show_ids=False, verbose=False, this=False, other=False,
4663
 
            include_merged=None, revision=None, my_revision=None,
4664
 
            directory=u'.',
4665
 
            include_merges=symbol_versioning.DEPRECATED_PARAMETER):
 
4301
            include_merges=False, revision=None, my_revision=None):
4666
4302
        from bzrlib.missing import find_unmerged, iter_log_revisions
4667
4303
        def message(s):
4668
4304
            if not is_quiet():
4669
4305
                self.outf.write(s)
4670
4306
 
4671
 
        if symbol_versioning.deprecated_passed(include_merges):
4672
 
            ui.ui_factory.show_user_warning(
4673
 
                'deprecated_command_option',
4674
 
                deprecated_name='--include-merges',
4675
 
                recommended_name='--include-merged',
4676
 
                deprecated_in_version='2.5',
4677
 
                command=self.invoked_as)
4678
 
            if include_merged is None:
4679
 
                include_merged = include_merges
4680
 
            else:
4681
 
                raise errors.BzrCommandError(gettext(
4682
 
                    '{0} and {1} are mutually exclusive').format(
4683
 
                    '--include-merges', '--include-merged'))
4684
 
        if include_merged is None:
4685
 
            include_merged = False
4686
4307
        if this:
4687
4308
            mine_only = this
4688
4309
        if other:
4696
4317
        elif theirs_only:
4697
4318
            restrict = 'remote'
4698
4319
 
4699
 
        local_branch = Branch.open_containing(directory)[0]
4700
 
        self.add_cleanup(local_branch.lock_read().unlock)
4701
 
 
 
4320
        local_branch = Branch.open_containing(u".")[0]
4702
4321
        parent = local_branch.get_parent()
4703
4322
        if other_branch is None:
4704
4323
            other_branch = parent
4705
4324
            if other_branch is None:
4706
 
                raise errors.BzrCommandError(gettext("No peer location known"
4707
 
                                             " or specified."))
 
4325
                raise errors.BzrCommandError("No peer location known"
 
4326
                                             " or specified.")
4708
4327
            display_url = urlutils.unescape_for_display(parent,
4709
4328
                                                        self.outf.encoding)
4710
 
            message(gettext("Using saved parent location: {0}\n").format(
4711
 
                    display_url))
 
4329
            message("Using saved parent location: "
 
4330
                    + display_url + "\n")
4712
4331
 
4713
4332
        remote_branch = Branch.open(other_branch)
4714
4333
        if remote_branch.base == local_branch.base:
4715
4334
            remote_branch = local_branch
4716
 
        else:
4717
 
            self.add_cleanup(remote_branch.lock_read().unlock)
4718
4335
 
4719
4336
        local_revid_range = _revision_range_to_revid_range(
4720
4337
            _get_revision_range(my_revision, local_branch,
4724
4341
            _get_revision_range(revision,
4725
4342
                remote_branch, self.name()))
4726
4343
 
4727
 
        local_extra, remote_extra = find_unmerged(
4728
 
            local_branch, remote_branch, restrict,
4729
 
            backward=not reverse,
4730
 
            include_merged=include_merged,
4731
 
            local_revid_range=local_revid_range,
4732
 
            remote_revid_range=remote_revid_range)
4733
 
 
4734
 
        if log_format is None:
4735
 
            registry = log.log_formatter_registry
4736
 
            log_format = registry.get_default(local_branch)
4737
 
        lf = log_format(to_file=self.outf,
4738
 
                        show_ids=show_ids,
4739
 
                        show_timezone='original')
4740
 
 
4741
 
        status_code = 0
4742
 
        if local_extra and not theirs_only:
4743
 
            message(ngettext("You have %d extra revision:\n",
4744
 
                             "You have %d extra revisions:\n", 
4745
 
                             len(local_extra)) %
4746
 
                len(local_extra))
4747
 
            for revision in iter_log_revisions(local_extra,
4748
 
                                local_branch.repository,
4749
 
                                verbose):
4750
 
                lf.log_revision(revision)
4751
 
            printed_local = True
4752
 
            status_code = 1
4753
 
        else:
4754
 
            printed_local = False
4755
 
 
4756
 
        if remote_extra and not mine_only:
4757
 
            if printed_local is True:
4758
 
                message("\n\n\n")
4759
 
            message(ngettext("You are missing %d revision:\n",
4760
 
                             "You are missing %d revisions:\n",
4761
 
                             len(remote_extra)) %
4762
 
                len(remote_extra))
4763
 
            for revision in iter_log_revisions(remote_extra,
4764
 
                                remote_branch.repository,
4765
 
                                verbose):
4766
 
                lf.log_revision(revision)
4767
 
            status_code = 1
4768
 
 
4769
 
        if mine_only and not local_extra:
4770
 
            # We checked local, and found nothing extra
4771
 
            message(gettext('This branch has no new revisions.\n'))
4772
 
        elif theirs_only and not remote_extra:
4773
 
            # We checked remote, and found nothing extra
4774
 
            message(gettext('Other branch has no new revisions.\n'))
4775
 
        elif not (mine_only or theirs_only or local_extra or
4776
 
                  remote_extra):
4777
 
            # We checked both branches, and neither one had extra
4778
 
            # revisions
4779
 
            message(gettext("Branches are up to date.\n"))
4780
 
        self.cleanup_now()
 
4344
        local_branch.lock_read()
 
4345
        try:
 
4346
            remote_branch.lock_read()
 
4347
            try:
 
4348
                local_extra, remote_extra = find_unmerged(
 
4349
                    local_branch, remote_branch, restrict,
 
4350
                    backward=not reverse,
 
4351
                    include_merges=include_merges,
 
4352
                    local_revid_range=local_revid_range,
 
4353
                    remote_revid_range=remote_revid_range)
 
4354
 
 
4355
                if log_format is None:
 
4356
                    registry = log.log_formatter_registry
 
4357
                    log_format = registry.get_default(local_branch)
 
4358
                lf = log_format(to_file=self.outf,
 
4359
                                show_ids=show_ids,
 
4360
                                show_timezone='original')
 
4361
 
 
4362
                status_code = 0
 
4363
                if local_extra and not theirs_only:
 
4364
                    message("You have %d extra revision(s):\n" %
 
4365
                        len(local_extra))
 
4366
                    for revision in iter_log_revisions(local_extra,
 
4367
                                        local_branch.repository,
 
4368
                                        verbose):
 
4369
                        lf.log_revision(revision)
 
4370
                    printed_local = True
 
4371
                    status_code = 1
 
4372
                else:
 
4373
                    printed_local = False
 
4374
 
 
4375
                if remote_extra and not mine_only:
 
4376
                    if printed_local is True:
 
4377
                        message("\n\n\n")
 
4378
                    message("You are missing %d revision(s):\n" %
 
4379
                        len(remote_extra))
 
4380
                    for revision in iter_log_revisions(remote_extra,
 
4381
                                        remote_branch.repository,
 
4382
                                        verbose):
 
4383
                        lf.log_revision(revision)
 
4384
                    status_code = 1
 
4385
 
 
4386
                if mine_only and not local_extra:
 
4387
                    # We checked local, and found nothing extra
 
4388
                    message('This branch is up to date.\n')
 
4389
                elif theirs_only and not remote_extra:
 
4390
                    # We checked remote, and found nothing extra
 
4391
                    message('Other branch is up to date.\n')
 
4392
                elif not (mine_only or theirs_only or local_extra or
 
4393
                          remote_extra):
 
4394
                    # We checked both branches, and neither one had extra
 
4395
                    # revisions
 
4396
                    message("Branches are up to date.\n")
 
4397
            finally:
 
4398
                remote_branch.unlock()
 
4399
        finally:
 
4400
            local_branch.unlock()
4781
4401
        if not status_code and parent is None and other_branch is not None:
4782
 
            self.add_cleanup(local_branch.lock_write().unlock)
4783
 
            # handle race conditions - a parent might be set while we run.
4784
 
            if local_branch.get_parent() is None:
4785
 
                local_branch.set_parent(remote_branch.base)
 
4402
            local_branch.lock_write()
 
4403
            try:
 
4404
                # handle race conditions - a parent might be set while we run.
 
4405
                if local_branch.get_parent() is None:
 
4406
                    local_branch.set_parent(remote_branch.base)
 
4407
            finally:
 
4408
                local_branch.unlock()
4786
4409
        return status_code
4787
4410
 
4788
4411
 
4789
4412
class cmd_pack(Command):
4790
 
    __doc__ = """Compress the data within a repository.
4791
 
 
4792
 
    This operation compresses the data within a bazaar repository. As
4793
 
    bazaar supports automatic packing of repository, this operation is
4794
 
    normally not required to be done manually.
4795
 
 
4796
 
    During the pack operation, bazaar takes a backup of existing repository
4797
 
    data, i.e. pack files. This backup is eventually removed by bazaar
4798
 
    automatically when it is safe to do so. To save disk space by removing
4799
 
    the backed up pack files, the --clean-obsolete-packs option may be
4800
 
    used.
4801
 
 
4802
 
    Warning: If you use --clean-obsolete-packs and your machine crashes
4803
 
    during or immediately after repacking, you may be left with a state
4804
 
    where the deletion has been written to disk but the new packs have not
4805
 
    been. In this case the repository may be unusable.
4806
 
    """
 
4413
    """Compress the data within a repository."""
4807
4414
 
4808
4415
    _see_also = ['repositories']
4809
4416
    takes_args = ['branch_or_repo?']
4810
 
    takes_options = [
4811
 
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4812
 
        ]
4813
4417
 
4814
 
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
 
4418
    def run(self, branch_or_repo='.'):
4815
4419
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4816
4420
        try:
4817
4421
            branch = dir.open_branch()
4818
4422
            repository = branch.repository
4819
4423
        except errors.NotBranchError:
4820
4424
            repository = dir.open_repository()
4821
 
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
4425
        repository.pack()
4822
4426
 
4823
4427
 
4824
4428
class cmd_plugins(Command):
4825
 
    __doc__ = """List the installed plugins.
 
4429
    """List the installed plugins.
4826
4430
 
4827
4431
    This command displays the list of installed plugins including
4828
4432
    version of plugin and a short description of each.
4835
4439
    adding new commands, providing additional network transports and
4836
4440
    customizing log output.
4837
4441
 
4838
 
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4839
 
    for further information on plugins including where to find them and how to
4840
 
    install them. Instructions are also provided there on how to write new
4841
 
    plugins using the Python programming language.
 
4442
    See the Bazaar web site, http://bazaar-vcs.org, for further
 
4443
    information on plugins including where to find them and how to
 
4444
    install them. Instructions are also provided there on how to
 
4445
    write new plugins using the Python programming language.
4842
4446
    """
4843
4447
    takes_options = ['verbose']
4844
4448
 
4845
4449
    @display_command
4846
4450
    def run(self, verbose=False):
4847
 
        from bzrlib import plugin
4848
 
        # Don't give writelines a generator as some codecs don't like that
4849
 
        self.outf.writelines(
4850
 
            list(plugin.describe_plugins(show_paths=verbose)))
 
4451
        import bzrlib.plugin
 
4452
        from inspect import getdoc
 
4453
        result = []
 
4454
        for name, plugin in bzrlib.plugin.plugins().items():
 
4455
            version = plugin.__version__
 
4456
            if version == 'unknown':
 
4457
                version = ''
 
4458
            name_ver = '%s %s' % (name, version)
 
4459
            d = getdoc(plugin.module)
 
4460
            if d:
 
4461
                doc = d.split('\n')[0]
 
4462
            else:
 
4463
                doc = '(no description)'
 
4464
            result.append((name_ver, doc, plugin.path()))
 
4465
        for name_ver, doc, path in sorted(result):
 
4466
            print name_ver
 
4467
            print '   ', doc
 
4468
            if verbose:
 
4469
                print '   ', path
 
4470
            print
4851
4471
 
4852
4472
 
4853
4473
class cmd_testament(Command):
4854
 
    __doc__ = """Show testament (signing-form) of a revision."""
 
4474
    """Show testament (signing-form) of a revision."""
4855
4475
    takes_options = [
4856
4476
            'revision',
4857
4477
            Option('long', help='Produce long-format testament.'),
4869
4489
            b = Branch.open_containing(branch)[0]
4870
4490
        else:
4871
4491
            b = Branch.open(branch)
4872
 
        self.add_cleanup(b.lock_read().unlock)
4873
 
        if revision is None:
4874
 
            rev_id = b.last_revision()
4875
 
        else:
4876
 
            rev_id = revision[0].as_revision_id(b)
4877
 
        t = testament_class.from_revision(b.repository, rev_id)
4878
 
        if long:
4879
 
            sys.stdout.writelines(t.as_text_lines())
4880
 
        else:
4881
 
            sys.stdout.write(t.as_short_text())
 
4492
        b.lock_read()
 
4493
        try:
 
4494
            if revision is None:
 
4495
                rev_id = b.last_revision()
 
4496
            else:
 
4497
                rev_id = revision[0].as_revision_id(b)
 
4498
            t = testament_class.from_revision(b.repository, rev_id)
 
4499
            if long:
 
4500
                sys.stdout.writelines(t.as_text_lines())
 
4501
            else:
 
4502
                sys.stdout.write(t.as_short_text())
 
4503
        finally:
 
4504
            b.unlock()
4882
4505
 
4883
4506
 
4884
4507
class cmd_annotate(Command):
4885
 
    __doc__ = """Show the origin of each line in a file.
 
4508
    """Show the origin of each line in a file.
4886
4509
 
4887
4510
    This prints out the given file with an annotation on the left side
4888
4511
    indicating which revision, author and date introduced the change.
4899
4522
                     Option('long', help='Show commit date in annotations.'),
4900
4523
                     'revision',
4901
4524
                     'show-ids',
4902
 
                     'directory',
4903
4525
                     ]
4904
4526
    encoding_type = 'exact'
4905
4527
 
4906
4528
    @display_command
4907
4529
    def run(self, filename, all=False, long=False, revision=None,
4908
 
            show_ids=False, directory=None):
4909
 
        from bzrlib.annotate import (
4910
 
            annotate_file_tree,
4911
 
            )
 
4530
            show_ids=False):
 
4531
        from bzrlib.annotate import annotate_file, annotate_file_tree
4912
4532
        wt, branch, relpath = \
4913
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4533
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
4914
4534
        if wt is not None:
4915
 
            self.add_cleanup(wt.lock_read().unlock)
4916
 
        else:
4917
 
            self.add_cleanup(branch.lock_read().unlock)
4918
 
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4919
 
        self.add_cleanup(tree.lock_read().unlock)
4920
 
        if wt is not None and revision is None:
4921
 
            file_id = wt.path2id(relpath)
4922
 
        else:
4923
 
            file_id = tree.path2id(relpath)
4924
 
        if file_id is None:
4925
 
            raise errors.NotVersionedError(filename)
4926
 
        if wt is not None and revision is None:
4927
 
            # If there is a tree and we're not annotating historical
4928
 
            # versions, annotate the working tree's content.
4929
 
            annotate_file_tree(wt, file_id, self.outf, long, all,
4930
 
                show_ids=show_ids)
4931
 
        else:
4932
 
            annotate_file_tree(tree, file_id, self.outf, long, all,
4933
 
                show_ids=show_ids, branch=branch)
 
4535
            wt.lock_read()
 
4536
        else:
 
4537
            branch.lock_read()
 
4538
        try:
 
4539
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
 
4540
            if wt is not None:
 
4541
                file_id = wt.path2id(relpath)
 
4542
            else:
 
4543
                file_id = tree.path2id(relpath)
 
4544
            if file_id is None:
 
4545
                raise errors.NotVersionedError(filename)
 
4546
            file_version = tree.inventory[file_id].revision
 
4547
            if wt is not None and revision is None:
 
4548
                # If there is a tree and we're not annotating historical
 
4549
                # versions, annotate the working tree's content.
 
4550
                annotate_file_tree(wt, file_id, self.outf, long, all,
 
4551
                    show_ids=show_ids)
 
4552
            else:
 
4553
                annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4554
                              show_ids=show_ids)
 
4555
        finally:
 
4556
            if wt is not None:
 
4557
                wt.unlock()
 
4558
            else:
 
4559
                branch.unlock()
4934
4560
 
4935
4561
 
4936
4562
class cmd_re_sign(Command):
4937
 
    __doc__ = """Create a digital signature for an existing revision."""
 
4563
    """Create a digital signature for an existing revision."""
4938
4564
    # TODO be able to replace existing ones.
4939
4565
 
4940
4566
    hidden = True # is this right ?
4941
4567
    takes_args = ['revision_id*']
4942
 
    takes_options = ['directory', 'revision']
 
4568
    takes_options = ['revision']
4943
4569
 
4944
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
4570
    def run(self, revision_id_list=None, revision=None):
4945
4571
        if revision_id_list is not None and revision is not None:
4946
 
            raise errors.BzrCommandError(gettext('You can only supply one of revision_id or --revision'))
 
4572
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4947
4573
        if revision_id_list is None and revision is None:
4948
 
            raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
4949
 
        b = WorkingTree.open_containing(directory)[0].branch
4950
 
        self.add_cleanup(b.lock_write().unlock)
4951
 
        return self._run(b, revision_id_list, revision)
 
4574
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
 
4575
        b = WorkingTree.open_containing(u'.')[0].branch
 
4576
        b.lock_write()
 
4577
        try:
 
4578
            return self._run(b, revision_id_list, revision)
 
4579
        finally:
 
4580
            b.unlock()
4952
4581
 
4953
4582
    def _run(self, b, revision_id_list, revision):
4954
4583
        import bzrlib.gpg as gpg
4983
4612
                if to_revid is None:
4984
4613
                    to_revno = b.revno()
4985
4614
                if from_revno is None or to_revno is None:
4986
 
                    raise errors.BzrCommandError(gettext('Cannot sign a range of non-revision-history revisions'))
 
4615
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
4987
4616
                b.repository.start_write_group()
4988
4617
                try:
4989
4618
                    for revno in range(from_revno, to_revno + 1):
4995
4624
                else:
4996
4625
                    b.repository.commit_write_group()
4997
4626
            else:
4998
 
                raise errors.BzrCommandError(gettext('Please supply either one revision, or a range.'))
 
4627
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
4999
4628
 
5000
4629
 
5001
4630
class cmd_bind(Command):
5002
 
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
5003
 
    If no branch is supplied, rebind to the last bound location.
 
4631
    """Convert the current branch into a checkout of the supplied branch.
5004
4632
 
5005
4633
    Once converted into a checkout, commits must succeed on the master branch
5006
4634
    before they will be applied to the local branch.
5012
4640
 
5013
4641
    _see_also = ['checkouts', 'unbind']
5014
4642
    takes_args = ['location?']
5015
 
    takes_options = ['directory']
 
4643
    takes_options = []
5016
4644
 
5017
 
    def run(self, location=None, directory=u'.'):
5018
 
        b, relpath = Branch.open_containing(directory)
 
4645
    def run(self, location=None):
 
4646
        b, relpath = Branch.open_containing(u'.')
5019
4647
        if location is None:
5020
4648
            try:
5021
4649
                location = b.get_old_bound_location()
5022
4650
            except errors.UpgradeRequired:
5023
 
                raise errors.BzrCommandError(gettext('No location supplied.  '
5024
 
                    'This format does not remember old locations.'))
 
4651
                raise errors.BzrCommandError('No location supplied.  '
 
4652
                    'This format does not remember old locations.')
5025
4653
            else:
5026
4654
                if location is None:
5027
 
                    if b.get_bound_location() is not None:
5028
 
                        raise errors.BzrCommandError(gettext('Branch is already bound'))
5029
 
                    else:
5030
 
                        raise errors.BzrCommandError(gettext('No location supplied '
5031
 
                            'and no previous location known'))
 
4655
                    raise errors.BzrCommandError('No location supplied and no '
 
4656
                        'previous location known')
5032
4657
        b_other = Branch.open(location)
5033
4658
        try:
5034
4659
            b.bind(b_other)
5035
4660
        except errors.DivergedBranches:
5036
 
            raise errors.BzrCommandError(gettext('These branches have diverged.'
5037
 
                                         ' Try merging, and then bind again.'))
 
4661
            raise errors.BzrCommandError('These branches have diverged.'
 
4662
                                         ' Try merging, and then bind again.')
5038
4663
        if b.get_config().has_explicit_nickname():
5039
4664
            b.nick = b_other.nick
5040
4665
 
5041
4666
 
5042
4667
class cmd_unbind(Command):
5043
 
    __doc__ = """Convert the current checkout into a regular branch.
 
4668
    """Convert the current checkout into a regular branch.
5044
4669
 
5045
4670
    After unbinding, the local branch is considered independent and subsequent
5046
4671
    commits will be local only.
5048
4673
 
5049
4674
    _see_also = ['checkouts', 'bind']
5050
4675
    takes_args = []
5051
 
    takes_options = ['directory']
 
4676
    takes_options = []
5052
4677
 
5053
 
    def run(self, directory=u'.'):
5054
 
        b, relpath = Branch.open_containing(directory)
 
4678
    def run(self):
 
4679
        b, relpath = Branch.open_containing(u'.')
5055
4680
        if not b.unbind():
5056
 
            raise errors.BzrCommandError(gettext('Local branch is not bound'))
 
4681
            raise errors.BzrCommandError('Local branch is not bound')
5057
4682
 
5058
4683
 
5059
4684
class cmd_uncommit(Command):
5060
 
    __doc__ = """Remove the last committed revision.
 
4685
    """Remove the last committed revision.
5061
4686
 
5062
4687
    --verbose will print out what is being removed.
5063
4688
    --dry-run will go through all the motions, but not actually
5080
4705
    takes_options = ['verbose', 'revision',
5081
4706
                    Option('dry-run', help='Don\'t actually make changes.'),
5082
4707
                    Option('force', help='Say yes to all questions.'),
5083
 
                    Option('keep-tags',
5084
 
                           help='Keep tags that point to removed revisions.'),
5085
4708
                    Option('local',
5086
4709
                           help="Only remove the commits from the local branch"
5087
4710
                                " when in a checkout."
5091
4714
    aliases = []
5092
4715
    encoding_type = 'replace'
5093
4716
 
5094
 
    def run(self, location=None, dry_run=False, verbose=False,
5095
 
            revision=None, force=False, local=False, keep_tags=False):
 
4717
    def run(self, location=None,
 
4718
            dry_run=False, verbose=False,
 
4719
            revision=None, force=False, local=False):
5096
4720
        if location is None:
5097
4721
            location = u'.'
5098
4722
        control, relpath = bzrdir.BzrDir.open_containing(location)
5104
4728
            b = control.open_branch()
5105
4729
 
5106
4730
        if tree is not None:
5107
 
            self.add_cleanup(tree.lock_write().unlock)
 
4731
            tree.lock_write()
5108
4732
        else:
5109
 
            self.add_cleanup(b.lock_write().unlock)
5110
 
        return self._run(b, tree, dry_run, verbose, revision, force,
5111
 
                         local, keep_tags)
 
4733
            b.lock_write()
 
4734
        try:
 
4735
            return self._run(b, tree, dry_run, verbose, revision, force,
 
4736
                             local=local)
 
4737
        finally:
 
4738
            if tree is not None:
 
4739
                tree.unlock()
 
4740
            else:
 
4741
                b.unlock()
5112
4742
 
5113
 
    def _run(self, b, tree, dry_run, verbose, revision, force, local,
5114
 
             keep_tags):
 
4743
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
5115
4744
        from bzrlib.log import log_formatter, show_log
5116
4745
        from bzrlib.uncommit import uncommit
5117
4746
 
5132
4761
                rev_id = b.get_rev_id(revno)
5133
4762
 
5134
4763
        if rev_id is None or _mod_revision.is_null(rev_id):
5135
 
            self.outf.write(gettext('No revisions to uncommit.\n'))
 
4764
            self.outf.write('No revisions to uncommit.\n')
5136
4765
            return 1
5137
4766
 
5138
4767
        lf = log_formatter('short',
5147
4776
                 end_revision=last_revno)
5148
4777
 
5149
4778
        if dry_run:
5150
 
            self.outf.write(gettext('Dry-run, pretending to remove'
5151
 
                            ' the above revisions.\n'))
 
4779
            print 'Dry-run, pretending to remove the above revisions.'
 
4780
            if not force:
 
4781
                val = raw_input('Press <enter> to continue')
5152
4782
        else:
5153
 
            self.outf.write(gettext('The above revision(s) will be removed.\n'))
5154
 
 
5155
 
        if not force:
5156
 
            if not ui.ui_factory.confirm_action(
5157
 
                    gettext(u'Uncommit these revisions'),
5158
 
                    'bzrlib.builtins.uncommit',
5159
 
                    {}):
5160
 
                self.outf.write(gettext('Canceled\n'))
5161
 
                return 0
 
4783
            print 'The above revision(s) will be removed.'
 
4784
            if not force:
 
4785
                val = raw_input('Are you sure [y/N]? ')
 
4786
                if val.lower() not in ('y', 'yes'):
 
4787
                    print 'Canceled'
 
4788
                    return 0
5162
4789
 
5163
4790
        mutter('Uncommitting from {%s} to {%s}',
5164
4791
               last_rev_id, rev_id)
5165
4792
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
5166
 
                 revno=revno, local=local, keep_tags=keep_tags)
5167
 
        self.outf.write(gettext('You can restore the old tip by running:\n'
5168
 
             '  bzr pull . -r revid:%s\n') % last_rev_id)
 
4793
                 revno=revno, local=local)
 
4794
        note('You can restore the old tip by running:\n'
 
4795
             '  bzr pull . -r revid:%s', last_rev_id)
5169
4796
 
5170
4797
 
5171
4798
class cmd_break_lock(Command):
5172
 
    __doc__ = """Break a dead lock.
5173
 
 
5174
 
    This command breaks a lock on a repository, branch, working directory or
5175
 
    config file.
 
4799
    """Break a dead lock on a repository, branch or working directory.
5176
4800
 
5177
4801
    CAUTION: Locks should only be broken when you are sure that the process
5178
4802
    holding the lock has been stopped.
5179
4803
 
5180
 
    You can get information on what locks are open via the 'bzr info
5181
 
    [location]' command.
 
4804
    You can get information on what locks are open via the 'bzr info' command.
5182
4805
 
5183
4806
    :Examples:
5184
4807
        bzr break-lock
5185
 
        bzr break-lock bzr+ssh://example.com/bzr/foo
5186
 
        bzr break-lock --conf ~/.bazaar
5187
4808
    """
5188
 
 
5189
4809
    takes_args = ['location?']
5190
 
    takes_options = [
5191
 
        Option('config',
5192
 
               help='LOCATION is the directory where the config lock is.'),
5193
 
        Option('force',
5194
 
            help='Do not ask for confirmation before breaking the lock.'),
5195
 
        ]
5196
4810
 
5197
 
    def run(self, location=None, config=False, force=False):
 
4811
    def run(self, location=None, show=False):
5198
4812
        if location is None:
5199
4813
            location = u'.'
5200
 
        if force:
5201
 
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5202
 
                None,
5203
 
                {'bzrlib.lockdir.break': True})
5204
 
        if config:
5205
 
            conf = _mod_config.LockableConfig(file_name=location)
5206
 
            conf.break_lock()
5207
 
        else:
5208
 
            control, relpath = bzrdir.BzrDir.open_containing(location)
5209
 
            try:
5210
 
                control.break_lock()
5211
 
            except NotImplementedError:
5212
 
                pass
 
4814
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4815
        try:
 
4816
            control.break_lock()
 
4817
        except NotImplementedError:
 
4818
            pass
5213
4819
 
5214
4820
 
5215
4821
class cmd_wait_until_signalled(Command):
5216
 
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4822
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
5217
4823
 
5218
4824
    This just prints a line to signal when it is ready, then blocks on stdin.
5219
4825
    """
5227
4833
 
5228
4834
 
5229
4835
class cmd_serve(Command):
5230
 
    __doc__ = """Run the bzr server."""
 
4836
    """Run the bzr server."""
5231
4837
 
5232
4838
    aliases = ['server']
5233
4839
 
5244
4850
                    'result in a dynamically allocated port.  The default port '
5245
4851
                    'depends on the protocol.',
5246
4852
               type=str),
5247
 
        custom_help('directory',
5248
 
               help='Serve contents of this directory.'),
 
4853
        Option('directory',
 
4854
               help='Serve contents of this directory.',
 
4855
               type=unicode),
5249
4856
        Option('allow-writes',
5250
4857
               help='By default the server is a readonly server.  Supplying '
5251
4858
                    '--allow-writes enables write access to the contents of '
5255
4862
                    'option leads to global uncontrolled write access to your '
5256
4863
                    'file system.'
5257
4864
                ),
5258
 
        Option('client-timeout', type=float,
5259
 
               help='Override the default idle client timeout (5min).'),
5260
4865
        ]
5261
4866
 
5262
4867
    def get_host_and_port(self, port):
5279
4884
        return host, port
5280
4885
 
5281
4886
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
5282
 
            protocol=None, client_timeout=None):
5283
 
        from bzrlib import transport
 
4887
            protocol=None):
 
4888
        from bzrlib.transport import get_transport, transport_server_registry
5284
4889
        if directory is None:
5285
4890
            directory = os.getcwd()
5286
4891
        if protocol is None:
5287
 
            protocol = transport.transport_server_registry.get()
 
4892
            protocol = transport_server_registry.get()
5288
4893
        host, port = self.get_host_and_port(port)
5289
4894
        url = urlutils.local_path_to_url(directory)
5290
4895
        if not allow_writes:
5291
4896
            url = 'readonly+' + url
5292
 
        t = transport.get_transport(url)
5293
 
        try:
5294
 
            protocol(t, host, port, inet, client_timeout)
5295
 
        except TypeError, e:
5296
 
            # We use symbol_versioning.deprecated_in just so that people
5297
 
            # grepping can find it here.
5298
 
            # symbol_versioning.deprecated_in((2, 5, 0))
5299
 
            symbol_versioning.warn(
5300
 
                'Got TypeError(%s)\ntrying to call protocol: %s.%s\n'
5301
 
                'Most likely it needs to be updated to support a'
5302
 
                ' "timeout" parameter (added in bzr 2.5.0)'
5303
 
                % (e, protocol.__module__, protocol),
5304
 
                DeprecationWarning)
5305
 
            protocol(t, host, port, inet)
 
4897
        transport = get_transport(url)
 
4898
        protocol(transport, host, port, inet)
5306
4899
 
5307
4900
 
5308
4901
class cmd_join(Command):
5309
 
    __doc__ = """Combine a tree into its containing tree.
 
4902
    """Combine a tree into its containing tree.
5310
4903
 
5311
4904
    This command requires the target tree to be in a rich-root format.
5312
4905
 
5314
4907
    not part of it.  (Such trees can be produced by "bzr split", but also by
5315
4908
    running "bzr branch" with the target inside a tree.)
5316
4909
 
5317
 
    The result is a combined tree, with the subtree no longer an independent
 
4910
    The result is a combined tree, with the subtree no longer an independant
5318
4911
    part.  This is marked as a merge of the subtree into the containing tree,
5319
4912
    and all history is preserved.
5320
4913
    """
5331
4924
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
5332
4925
        repo = containing_tree.branch.repository
5333
4926
        if not repo.supports_rich_root():
5334
 
            raise errors.BzrCommandError(gettext(
 
4927
            raise errors.BzrCommandError(
5335
4928
                "Can't join trees because %s doesn't support rich root data.\n"
5336
 
                "You can use bzr upgrade on the repository.")
 
4929
                "You can use bzr upgrade on the repository."
5337
4930
                % (repo,))
5338
4931
        if reference:
5339
4932
            try:
5341
4934
            except errors.BadReferenceTarget, e:
5342
4935
                # XXX: Would be better to just raise a nicely printable
5343
4936
                # exception from the real origin.  Also below.  mbp 20070306
5344
 
                raise errors.BzrCommandError(
5345
 
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
4937
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
4938
                                             (tree, e.reason))
5346
4939
        else:
5347
4940
            try:
5348
4941
                containing_tree.subsume(sub_tree)
5349
4942
            except errors.BadSubsumeSource, e:
5350
 
                raise errors.BzrCommandError(
5351
 
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
 
4943
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
4944
                                             (tree, e.reason))
5352
4945
 
5353
4946
 
5354
4947
class cmd_split(Command):
5355
 
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
4948
    """Split a subdirectory of a tree into a separate tree.
5356
4949
 
5357
4950
    This command will produce a target tree in a format that supports
5358
4951
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
5378
4971
 
5379
4972
 
5380
4973
class cmd_merge_directive(Command):
5381
 
    __doc__ = """Generate a merge directive for auto-merge tools.
 
4974
    """Generate a merge directive for auto-merge tools.
5382
4975
 
5383
4976
    A directive requests a merge to be performed, and also provides all the
5384
4977
    information necessary to do so.  This means it must either include a
5401
4994
    _see_also = ['send']
5402
4995
 
5403
4996
    takes_options = [
5404
 
        'directory',
5405
4997
        RegistryOption.from_kwargs('patch-type',
5406
4998
            'The type of patch to include in the directive.',
5407
4999
            title='Patch type',
5420
5012
    encoding_type = 'exact'
5421
5013
 
5422
5014
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5423
 
            sign=False, revision=None, mail_to=None, message=None,
5424
 
            directory=u'.'):
 
5015
            sign=False, revision=None, mail_to=None, message=None):
5425
5016
        from bzrlib.revision import ensure_null, NULL_REVISION
5426
5017
        include_patch, include_bundle = {
5427
5018
            'plain': (False, False),
5428
5019
            'diff': (True, False),
5429
5020
            'bundle': (True, True),
5430
5021
            }[patch_type]
5431
 
        branch = Branch.open(directory)
 
5022
        branch = Branch.open('.')
5432
5023
        stored_submit_branch = branch.get_submit_branch()
5433
5024
        if submit_branch is None:
5434
5025
            submit_branch = stored_submit_branch
5438
5029
        if submit_branch is None:
5439
5030
            submit_branch = branch.get_parent()
5440
5031
        if submit_branch is None:
5441
 
            raise errors.BzrCommandError(gettext('No submit branch specified or known'))
 
5032
            raise errors.BzrCommandError('No submit branch specified or known')
5442
5033
 
5443
5034
        stored_public_branch = branch.get_public_branch()
5444
5035
        if public_branch is None:
5446
5037
        elif stored_public_branch is None:
5447
5038
            branch.set_public_branch(public_branch)
5448
5039
        if not include_bundle and public_branch is None:
5449
 
            raise errors.BzrCommandError(gettext('No public branch specified or'
5450
 
                                         ' known'))
 
5040
            raise errors.BzrCommandError('No public branch specified or'
 
5041
                                         ' known')
5451
5042
        base_revision_id = None
5452
5043
        if revision is not None:
5453
5044
            if len(revision) > 2:
5454
 
                raise errors.BzrCommandError(gettext('bzr merge-directive takes '
5455
 
                    'at most two one revision identifiers'))
 
5045
                raise errors.BzrCommandError('bzr merge-directive takes '
 
5046
                    'at most two one revision identifiers')
5456
5047
            revision_id = revision[-1].as_revision_id(branch)
5457
5048
            if len(revision) == 2:
5458
5049
                base_revision_id = revision[0].as_revision_id(branch)
5460
5051
            revision_id = branch.last_revision()
5461
5052
        revision_id = ensure_null(revision_id)
5462
5053
        if revision_id == NULL_REVISION:
5463
 
            raise errors.BzrCommandError(gettext('No revisions to bundle.'))
 
5054
            raise errors.BzrCommandError('No revisions to bundle.')
5464
5055
        directive = merge_directive.MergeDirective2.from_objects(
5465
5056
            branch.repository, revision_id, time.time(),
5466
5057
            osutils.local_time_offset(), submit_branch,
5479
5070
 
5480
5071
 
5481
5072
class cmd_send(Command):
5482
 
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
5073
    """Mail or create a merge-directive for submitting changes.
5483
5074
 
5484
5075
    A merge directive provides many things needed for requesting merges:
5485
5076
 
5491
5082
      directly from the merge directive, without retrieving data from a
5492
5083
      branch.
5493
5084
 
5494
 
    `bzr send` creates a compact data set that, when applied using bzr
5495
 
    merge, has the same effect as merging from the source branch.  
5496
 
    
5497
 
    By default the merge directive is self-contained and can be applied to any
5498
 
    branch containing submit_branch in its ancestory without needing access to
5499
 
    the source branch.
5500
 
    
5501
 
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
5502
 
    revisions, but only a structured request to merge from the
5503
 
    public_location.  In that case the public_branch is needed and it must be
5504
 
    up-to-date and accessible to the recipient.  The public_branch is always
5505
 
    included if known, so that people can check it later.
5506
 
 
5507
 
    The submit branch defaults to the parent of the source branch, but can be
5508
 
    overridden.  Both submit branch and public branch will be remembered in
5509
 
    branch.conf the first time they are used for a particular branch.  The
5510
 
    source branch defaults to that containing the working directory, but can
5511
 
    be changed using --from.
5512
 
 
5513
 
    Both the submit branch and the public branch follow the usual behavior with
5514
 
    respect to --remember: If there is no default location set, the first send
5515
 
    will set it (use --no-remember to avoid setting it). After that, you can
5516
 
    omit the location to use the default.  To change the default, use
5517
 
    --remember. The value will only be saved if the location can be accessed.
5518
 
 
5519
 
    In order to calculate those changes, bzr must analyse the submit branch.
5520
 
    Therefore it is most efficient for the submit branch to be a local mirror.
5521
 
    If a public location is known for the submit_branch, that location is used
5522
 
    in the merge directive.
5523
 
 
5524
 
    The default behaviour is to send the merge directive by mail, unless -o is
5525
 
    given, in which case it is sent to a file.
 
5085
    If --no-bundle is specified, then public_branch is needed (and must be
 
5086
    up-to-date), so that the receiver can perform the merge using the
 
5087
    public_branch.  The public_branch is always included if known, so that
 
5088
    people can check it later.
 
5089
 
 
5090
    The submit branch defaults to the parent, but can be overridden.  Both
 
5091
    submit branch and public branch will be remembered if supplied.
 
5092
 
 
5093
    If a public_branch is known for the submit_branch, that public submit
 
5094
    branch is used in the merge instructions.  This means that a local mirror
 
5095
    can be used as your actual submit branch, once you have set public_branch
 
5096
    for that mirror.
5526
5097
 
5527
5098
    Mail is sent using your preferred mail program.  This should be transparent
5528
 
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
5099
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
5529
5100
    If the preferred client can't be found (or used), your editor will be used.
5530
5101
 
5531
5102
    To use a specific mail program, set the mail_client configuration option.
5548
5119
 
5549
5120
    The merge directives created by bzr send may be applied using bzr merge or
5550
5121
    bzr pull by specifying a file containing a merge directive as the location.
5551
 
 
5552
 
    bzr send makes extensive use of public locations to map local locations into
5553
 
    URLs that can be used by other people.  See `bzr help configuration` to
5554
 
    set them, and use `bzr info` to display them.
5555
5122
    """
5556
5123
 
5557
5124
    encoding_type = 'exact'
5573
5140
               short_name='f',
5574
5141
               type=unicode),
5575
5142
        Option('output', short_name='o',
5576
 
               help='Write merge directive to this file or directory; '
 
5143
               help='Write merge directive to this file; '
5577
5144
                    'use - for stdout.',
5578
5145
               type=unicode),
5579
5146
        Option('strict',
5590
5157
        ]
5591
5158
 
5592
5159
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5593
 
            no_patch=False, revision=None, remember=None, output=None,
 
5160
            no_patch=False, revision=None, remember=False, output=None,
5594
5161
            format=None, mail_to=None, message=None, body=None,
5595
5162
            strict=None, **kwargs):
5596
5163
        from bzrlib.send import send
5602
5169
 
5603
5170
 
5604
5171
class cmd_bundle_revisions(cmd_send):
5605
 
    __doc__ = """Create a merge-directive for submitting changes.
 
5172
    """Create a merge-directive for submitting changes.
5606
5173
 
5607
5174
    A merge directive provides many things needed for requesting merges:
5608
5175
 
5675
5242
 
5676
5243
 
5677
5244
class cmd_tag(Command):
5678
 
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5245
    """Create, remove or modify a tag naming a revision.
5679
5246
 
5680
5247
    Tags give human-meaningful names to revisions.  Commands that take a -r
5681
5248
    (--revision) option can be given -rtag:X, where X is any previously
5689
5256
 
5690
5257
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
5691
5258
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5692
 
 
5693
 
    If no tag name is specified it will be determined through the 
5694
 
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
5695
 
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
5696
 
    details.
5697
5259
    """
5698
5260
 
5699
5261
    _see_also = ['commit', 'tags']
5700
 
    takes_args = ['tag_name?']
 
5262
    takes_args = ['tag_name']
5701
5263
    takes_options = [
5702
5264
        Option('delete',
5703
5265
            help='Delete this tag rather than placing it.',
5704
5266
            ),
5705
 
        custom_help('directory',
5706
 
            help='Branch in which to place the tag.'),
 
5267
        Option('directory',
 
5268
            help='Branch in which to place the tag.',
 
5269
            short_name='d',
 
5270
            type=unicode,
 
5271
            ),
5707
5272
        Option('force',
5708
5273
            help='Replace existing tags.',
5709
5274
            ),
5710
5275
        'revision',
5711
5276
        ]
5712
5277
 
5713
 
    def run(self, tag_name=None,
 
5278
    def run(self, tag_name,
5714
5279
            delete=None,
5715
5280
            directory='.',
5716
5281
            force=None,
5717
5282
            revision=None,
5718
5283
            ):
5719
5284
        branch, relpath = Branch.open_containing(directory)
5720
 
        self.add_cleanup(branch.lock_write().unlock)
5721
 
        if delete:
5722
 
            if tag_name is None:
5723
 
                raise errors.BzrCommandError(gettext("No tag specified to delete."))
5724
 
            branch.tags.delete_tag(tag_name)
5725
 
            note(gettext('Deleted tag %s.') % tag_name)
5726
 
        else:
5727
 
            if revision:
5728
 
                if len(revision) != 1:
5729
 
                    raise errors.BzrCommandError(gettext(
5730
 
                        "Tags can only be placed on a single revision, "
5731
 
                        "not on a range"))
5732
 
                revision_id = revision[0].as_revision_id(branch)
5733
 
            else:
5734
 
                revision_id = branch.last_revision()
5735
 
            if tag_name is None:
5736
 
                tag_name = branch.automatic_tag_name(revision_id)
5737
 
                if tag_name is None:
5738
 
                    raise errors.BzrCommandError(gettext(
5739
 
                        "Please specify a tag name."))
5740
 
            try:
5741
 
                existing_target = branch.tags.lookup_tag(tag_name)
5742
 
            except errors.NoSuchTag:
5743
 
                existing_target = None
5744
 
            if not force and existing_target not in (None, revision_id):
5745
 
                raise errors.TagAlreadyExists(tag_name)
5746
 
            if existing_target == revision_id:
5747
 
                note(gettext('Tag %s already exists for that revision.') % tag_name)
5748
 
            else:
 
5285
        branch.lock_write()
 
5286
        try:
 
5287
            if delete:
 
5288
                branch.tags.delete_tag(tag_name)
 
5289
                self.outf.write('Deleted tag %s.\n' % tag_name)
 
5290
            else:
 
5291
                if revision:
 
5292
                    if len(revision) != 1:
 
5293
                        raise errors.BzrCommandError(
 
5294
                            "Tags can only be placed on a single revision, "
 
5295
                            "not on a range")
 
5296
                    revision_id = revision[0].as_revision_id(branch)
 
5297
                else:
 
5298
                    revision_id = branch.last_revision()
 
5299
                if (not force) and branch.tags.has_tag(tag_name):
 
5300
                    raise errors.TagAlreadyExists(tag_name)
5749
5301
                branch.tags.set_tag(tag_name, revision_id)
5750
 
                if existing_target is None:
5751
 
                    note(gettext('Created tag %s.') % tag_name)
5752
 
                else:
5753
 
                    note(gettext('Updated tag %s.') % tag_name)
 
5302
                self.outf.write('Created tag %s.\n' % tag_name)
 
5303
        finally:
 
5304
            branch.unlock()
5754
5305
 
5755
5306
 
5756
5307
class cmd_tags(Command):
5757
 
    __doc__ = """List tags.
 
5308
    """List tags.
5758
5309
 
5759
5310
    This command shows a table of tag names and the revisions they reference.
5760
5311
    """
5761
5312
 
5762
5313
    _see_also = ['tag']
5763
5314
    takes_options = [
5764
 
        custom_help('directory',
5765
 
            help='Branch whose tags should be displayed.'),
5766
 
        RegistryOption('sort',
 
5315
        Option('directory',
 
5316
            help='Branch whose tags should be displayed.',
 
5317
            short_name='d',
 
5318
            type=unicode,
 
5319
            ),
 
5320
        RegistryOption.from_kwargs('sort',
5767
5321
            'Sort tags by different criteria.', title='Sorting',
5768
 
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
 
5322
            alpha='Sort tags lexicographically (default).',
 
5323
            time='Sort tags chronologically.',
5769
5324
            ),
5770
5325
        'show-ids',
5771
5326
        'revision',
5772
5327
    ]
5773
5328
 
5774
5329
    @display_command
5775
 
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
5776
 
        from bzrlib.tag import tag_sort_methods
 
5330
    def run(self,
 
5331
            directory='.',
 
5332
            sort='alpha',
 
5333
            show_ids=False,
 
5334
            revision=None,
 
5335
            ):
5777
5336
        branch, relpath = Branch.open_containing(directory)
5778
5337
 
5779
5338
        tags = branch.tags.get_tag_dict().items()
5780
5339
        if not tags:
5781
5340
            return
5782
5341
 
5783
 
        self.add_cleanup(branch.lock_read().unlock)
5784
 
        if revision:
5785
 
            # Restrict to the specified range
5786
 
            tags = self._tags_for_range(branch, revision)
5787
 
        if sort is None:
5788
 
            sort = tag_sort_methods.get()
5789
 
        sort(branch, tags)
5790
 
        if not show_ids:
5791
 
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5792
 
            for index, (tag, revid) in enumerate(tags):
5793
 
                try:
5794
 
                    revno = branch.revision_id_to_dotted_revno(revid)
5795
 
                    if isinstance(revno, tuple):
5796
 
                        revno = '.'.join(map(str, revno))
5797
 
                except (errors.NoSuchRevision,
5798
 
                        errors.GhostRevisionsHaveNoRevno):
5799
 
                    # Bad tag data/merges can lead to tagged revisions
5800
 
                    # which are not in this branch. Fail gracefully ...
5801
 
                    revno = '?'
5802
 
                tags[index] = (tag, revno)
5803
 
        self.cleanup_now()
 
5342
        branch.lock_read()
 
5343
        try:
 
5344
            if revision:
 
5345
                graph = branch.repository.get_graph()
 
5346
                rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5347
                revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5348
                # only show revisions between revid1 and revid2 (inclusive)
 
5349
                tags = [(tag, revid) for tag, revid in tags if
 
5350
                    graph.is_between(revid, revid1, revid2)]
 
5351
            if sort == 'alpha':
 
5352
                tags.sort()
 
5353
            elif sort == 'time':
 
5354
                timestamps = {}
 
5355
                for tag, revid in tags:
 
5356
                    try:
 
5357
                        revobj = branch.repository.get_revision(revid)
 
5358
                    except errors.NoSuchRevision:
 
5359
                        timestamp = sys.maxint # place them at the end
 
5360
                    else:
 
5361
                        timestamp = revobj.timestamp
 
5362
                    timestamps[revid] = timestamp
 
5363
                tags.sort(key=lambda x: timestamps[x[1]])
 
5364
            if not show_ids:
 
5365
                # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
5366
                for index, (tag, revid) in enumerate(tags):
 
5367
                    try:
 
5368
                        revno = branch.revision_id_to_dotted_revno(revid)
 
5369
                        if isinstance(revno, tuple):
 
5370
                            revno = '.'.join(map(str, revno))
 
5371
                    except errors.NoSuchRevision:
 
5372
                        # Bad tag data/merges can lead to tagged revisions
 
5373
                        # which are not in this branch. Fail gracefully ...
 
5374
                        revno = '?'
 
5375
                    tags[index] = (tag, revno)
 
5376
        finally:
 
5377
            branch.unlock()
5804
5378
        for tag, revspec in tags:
5805
5379
            self.outf.write('%-20s %s\n' % (tag, revspec))
5806
5380
 
5807
 
    def _tags_for_range(self, branch, revision):
5808
 
        range_valid = True
5809
 
        rev1, rev2 = _get_revision_range(revision, branch, self.name())
5810
 
        revid1, revid2 = rev1.rev_id, rev2.rev_id
5811
 
        # _get_revision_range will always set revid2 if it's not specified.
5812
 
        # If revid1 is None, it means we want to start from the branch
5813
 
        # origin which is always a valid ancestor. If revid1 == revid2, the
5814
 
        # ancestry check is useless.
5815
 
        if revid1 and revid1 != revid2:
5816
 
            # FIXME: We really want to use the same graph than
5817
 
            # branch.iter_merge_sorted_revisions below, but this is not
5818
 
            # easily available -- vila 2011-09-23
5819
 
            if branch.repository.get_graph().is_ancestor(revid2, revid1):
5820
 
                # We don't want to output anything in this case...
5821
 
                return []
5822
 
        # only show revisions between revid1 and revid2 (inclusive)
5823
 
        tagged_revids = branch.tags.get_reverse_tag_dict()
5824
 
        found = []
5825
 
        for r in branch.iter_merge_sorted_revisions(
5826
 
            start_revision_id=revid2, stop_revision_id=revid1,
5827
 
            stop_rule='include'):
5828
 
            revid_tags = tagged_revids.get(r[0], None)
5829
 
            if revid_tags:
5830
 
                found.extend([(tag, r[0]) for tag in revid_tags])
5831
 
        return found
5832
 
 
5833
5381
 
5834
5382
class cmd_reconfigure(Command):
5835
 
    __doc__ = """Reconfigure the type of a bzr directory.
 
5383
    """Reconfigure the type of a bzr directory.
5836
5384
 
5837
5385
    A target configuration must be specified.
5838
5386
 
5849
5397
    takes_args = ['location?']
5850
5398
    takes_options = [
5851
5399
        RegistryOption.from_kwargs(
5852
 
            'tree_type',
5853
 
            title='Tree type',
5854
 
            help='The relation between branch and tree.',
 
5400
            'target_type',
 
5401
            title='Target type',
 
5402
            help='The type to reconfigure the directory to.',
5855
5403
            value_switches=True, enum_switch=False,
5856
5404
            branch='Reconfigure to be an unbound branch with no working tree.',
5857
5405
            tree='Reconfigure to be an unbound branch with a working tree.',
5858
5406
            checkout='Reconfigure to be a bound branch with a working tree.',
5859
5407
            lightweight_checkout='Reconfigure to be a lightweight'
5860
5408
                ' checkout (with no local history).',
5861
 
            ),
5862
 
        RegistryOption.from_kwargs(
5863
 
            'repository_type',
5864
 
            title='Repository type',
5865
 
            help='Location fo the repository.',
5866
 
            value_switches=True, enum_switch=False,
5867
5409
            standalone='Reconfigure to be a standalone branch '
5868
5410
                '(i.e. stop using shared repository).',
5869
5411
            use_shared='Reconfigure to use a shared repository.',
5870
 
            ),
5871
 
        RegistryOption.from_kwargs(
5872
 
            'repository_trees',
5873
 
            title='Trees in Repository',
5874
 
            help='Whether new branches in the repository have trees.',
5875
 
            value_switches=True, enum_switch=False,
5876
5412
            with_trees='Reconfigure repository to create '
5877
5413
                'working trees on branches by default.',
5878
5414
            with_no_trees='Reconfigure repository to not create '
5892
5428
            ),
5893
5429
        ]
5894
5430
 
5895
 
    def run(self, location=None, bind_to=None, force=False,
5896
 
            tree_type=None, repository_type=None, repository_trees=None,
5897
 
            stacked_on=None, unstacked=None):
 
5431
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5432
            stacked_on=None,
 
5433
            unstacked=None):
5898
5434
        directory = bzrdir.BzrDir.open(location)
5899
5435
        if stacked_on and unstacked:
5900
 
            raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
 
5436
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5901
5437
        elif stacked_on is not None:
5902
5438
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5903
5439
        elif unstacked:
5905
5441
        # At the moment you can use --stacked-on and a different
5906
5442
        # reconfiguration shape at the same time; there seems no good reason
5907
5443
        # to ban it.
5908
 
        if (tree_type is None and
5909
 
            repository_type is None and
5910
 
            repository_trees is None):
 
5444
        if target_type is None:
5911
5445
            if stacked_on or unstacked:
5912
5446
                return
5913
5447
            else:
5914
 
                raise errors.BzrCommandError(gettext('No target configuration '
5915
 
                    'specified'))
5916
 
        reconfiguration = None
5917
 
        if tree_type == 'branch':
 
5448
                raise errors.BzrCommandError('No target configuration '
 
5449
                    'specified')
 
5450
        elif target_type == 'branch':
5918
5451
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5919
 
        elif tree_type == 'tree':
 
5452
        elif target_type == 'tree':
5920
5453
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5921
 
        elif tree_type == 'checkout':
 
5454
        elif target_type == 'checkout':
5922
5455
            reconfiguration = reconfigure.Reconfigure.to_checkout(
5923
5456
                directory, bind_to)
5924
 
        elif tree_type == 'lightweight-checkout':
 
5457
        elif target_type == 'lightweight-checkout':
5925
5458
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5926
5459
                directory, bind_to)
5927
 
        if reconfiguration:
5928
 
            reconfiguration.apply(force)
5929
 
            reconfiguration = None
5930
 
        if repository_type == 'use-shared':
 
5460
        elif target_type == 'use-shared':
5931
5461
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5932
 
        elif repository_type == 'standalone':
 
5462
        elif target_type == 'standalone':
5933
5463
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5934
 
        if reconfiguration:
5935
 
            reconfiguration.apply(force)
5936
 
            reconfiguration = None
5937
 
        if repository_trees == 'with-trees':
 
5464
        elif target_type == 'with-trees':
5938
5465
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5939
5466
                directory, True)
5940
 
        elif repository_trees == 'with-no-trees':
 
5467
        elif target_type == 'with-no-trees':
5941
5468
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5942
5469
                directory, False)
5943
 
        if reconfiguration:
5944
 
            reconfiguration.apply(force)
5945
 
            reconfiguration = None
 
5470
        reconfiguration.apply(force)
5946
5471
 
5947
5472
 
5948
5473
class cmd_switch(Command):
5949
 
    __doc__ = """Set the branch of a checkout and update.
 
5474
    """Set the branch of a checkout and update.
5950
5475
 
5951
5476
    For lightweight checkouts, this changes the branch being referenced.
5952
5477
    For heavyweight checkouts, this checks that there are no local commits
5968
5493
    that of the master.
5969
5494
    """
5970
5495
 
5971
 
    takes_args = ['to_location?']
5972
 
    takes_options = ['directory',
5973
 
                     Option('force',
 
5496
    takes_args = ['to_location']
 
5497
    takes_options = [Option('force',
5974
5498
                        help='Switch even if local commits will be lost.'),
5975
 
                     'revision',
5976
5499
                     Option('create-branch', short_name='b',
5977
5500
                        help='Create the target branch from this one before'
5978
5501
                             ' switching to it.'),
5979
 
                    ]
 
5502
                     ]
5980
5503
 
5981
 
    def run(self, to_location=None, force=False, create_branch=False,
5982
 
            revision=None, directory=u'.'):
 
5504
    def run(self, to_location, force=False, create_branch=False):
5983
5505
        from bzrlib import switch
5984
 
        tree_location = directory
5985
 
        revision = _get_one_revision('switch', revision)
 
5506
        tree_location = '.'
5986
5507
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5987
 
        if to_location is None:
5988
 
            if revision is None:
5989
 
                raise errors.BzrCommandError(gettext('You must supply either a'
5990
 
                                             ' revision or a location'))
5991
 
            to_location = tree_location
5992
5508
        try:
5993
5509
            branch = control_dir.open_branch()
5994
5510
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5997
5513
            had_explicit_nick = False
5998
5514
        if create_branch:
5999
5515
            if branch is None:
6000
 
                raise errors.BzrCommandError(gettext('cannot create branch without'
6001
 
                                             ' source branch'))
 
5516
                raise errors.BzrCommandError('cannot create branch without'
 
5517
                                             ' source branch')
6002
5518
            to_location = directory_service.directories.dereference(
6003
5519
                              to_location)
6004
5520
            if '/' not in to_location and '\\' not in to_location:
6008
5524
            to_branch = branch.bzrdir.sprout(to_location,
6009
5525
                                 possible_transports=[branch.bzrdir.root_transport],
6010
5526
                                 source_branch=branch).open_branch()
 
5527
            # try:
 
5528
            #     from_branch = control_dir.open_branch()
 
5529
            # except errors.NotBranchError:
 
5530
            #     raise BzrCommandError('Cannot create a branch from this'
 
5531
            #         ' location when we cannot open this branch')
 
5532
            # from_branch.bzrdir.sprout(
 
5533
            pass
6011
5534
        else:
6012
5535
            try:
6013
5536
                to_branch = Branch.open(to_location)
6015
5538
                this_url = self._get_branch_location(control_dir)
6016
5539
                to_branch = Branch.open(
6017
5540
                    urlutils.join(this_url, '..', to_location))
6018
 
        if revision is not None:
6019
 
            revision = revision.as_revision_id(to_branch)
6020
 
        switch.switch(control_dir, to_branch, force, revision_id=revision)
 
5541
        switch.switch(control_dir, to_branch, force)
6021
5542
        if had_explicit_nick:
6022
5543
            branch = control_dir.open_branch() #get the new branch!
6023
5544
            branch.nick = to_branch.nick
6024
 
        note(gettext('Switched to branch: %s'),
 
5545
        note('Switched to branch: %s',
6025
5546
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
6026
5547
 
6027
5548
    def _get_branch_location(self, control_dir):
6043
5564
 
6044
5565
 
6045
5566
class cmd_view(Command):
6046
 
    __doc__ = """Manage filtered views.
 
5567
    """Manage filtered views.
6047
5568
 
6048
5569
    Views provide a mask over the tree so that users can focus on
6049
5570
    a subset of a tree when doing their work. After creating a view,
6129
5650
            name=None,
6130
5651
            switch=None,
6131
5652
            ):
6132
 
        tree, file_list = WorkingTree.open_containing_paths(file_list,
6133
 
            apply_view=False)
 
5653
        tree, file_list = tree_files(file_list, apply_view=False)
6134
5654
        current_view, view_dict = tree.views.get_view_info()
6135
5655
        if name is None:
6136
5656
            name = current_view
6137
5657
        if delete:
6138
5658
            if file_list:
6139
 
                raise errors.BzrCommandError(gettext(
6140
 
                    "Both --delete and a file list specified"))
 
5659
                raise errors.BzrCommandError(
 
5660
                    "Both --delete and a file list specified")
6141
5661
            elif switch:
6142
 
                raise errors.BzrCommandError(gettext(
6143
 
                    "Both --delete and --switch specified"))
 
5662
                raise errors.BzrCommandError(
 
5663
                    "Both --delete and --switch specified")
6144
5664
            elif all:
6145
5665
                tree.views.set_view_info(None, {})
6146
 
                self.outf.write(gettext("Deleted all views.\n"))
 
5666
                self.outf.write("Deleted all views.\n")
6147
5667
            elif name is None:
6148
 
                raise errors.BzrCommandError(gettext("No current view to delete"))
 
5668
                raise errors.BzrCommandError("No current view to delete")
6149
5669
            else:
6150
5670
                tree.views.delete_view(name)
6151
 
                self.outf.write(gettext("Deleted '%s' view.\n") % name)
 
5671
                self.outf.write("Deleted '%s' view.\n" % name)
6152
5672
        elif switch:
6153
5673
            if file_list:
6154
 
                raise errors.BzrCommandError(gettext(
6155
 
                    "Both --switch and a file list specified"))
 
5674
                raise errors.BzrCommandError(
 
5675
                    "Both --switch and a file list specified")
6156
5676
            elif all:
6157
 
                raise errors.BzrCommandError(gettext(
6158
 
                    "Both --switch and --all specified"))
 
5677
                raise errors.BzrCommandError(
 
5678
                    "Both --switch and --all specified")
6159
5679
            elif switch == 'off':
6160
5680
                if current_view is None:
6161
 
                    raise errors.BzrCommandError(gettext("No current view to disable"))
 
5681
                    raise errors.BzrCommandError("No current view to disable")
6162
5682
                tree.views.set_view_info(None, view_dict)
6163
 
                self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
 
5683
                self.outf.write("Disabled '%s' view.\n" % (current_view))
6164
5684
            else:
6165
5685
                tree.views.set_view_info(switch, view_dict)
6166
5686
                view_str = views.view_display_str(tree.views.lookup_view())
6167
 
                self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
 
5687
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
6168
5688
        elif all:
6169
5689
            if view_dict:
6170
 
                self.outf.write(gettext('Views defined:\n'))
 
5690
                self.outf.write('Views defined:\n')
6171
5691
                for view in sorted(view_dict):
6172
5692
                    if view == current_view:
6173
5693
                        active = "=>"
6176
5696
                    view_str = views.view_display_str(view_dict[view])
6177
5697
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
6178
5698
            else:
6179
 
                self.outf.write(gettext('No views defined.\n'))
 
5699
                self.outf.write('No views defined.\n')
6180
5700
        elif file_list:
6181
5701
            if name is None:
6182
5702
                # No name given and no current view set
6183
5703
                name = 'my'
6184
5704
            elif name == 'off':
6185
 
                raise errors.BzrCommandError(gettext(
6186
 
                    "Cannot change the 'off' pseudo view"))
 
5705
                raise errors.BzrCommandError(
 
5706
                    "Cannot change the 'off' pseudo view")
6187
5707
            tree.views.set_view(name, sorted(file_list))
6188
5708
            view_str = views.view_display_str(tree.views.lookup_view())
6189
 
            self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
 
5709
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
6190
5710
        else:
6191
5711
            # list the files
6192
5712
            if name is None:
6193
5713
                # No name given and no current view set
6194
 
                self.outf.write(gettext('No current view.\n'))
 
5714
                self.outf.write('No current view.\n')
6195
5715
            else:
6196
5716
                view_str = views.view_display_str(tree.views.lookup_view(name))
6197
 
                self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
 
5717
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
6198
5718
 
6199
5719
 
6200
5720
class cmd_hooks(Command):
6201
 
    __doc__ = """Show hooks."""
 
5721
    """Show hooks."""
6202
5722
 
6203
5723
    hidden = True
6204
5724
 
6214
5734
                        self.outf.write("    %s\n" %
6215
5735
                                        (some_hooks.get_hook_name(hook),))
6216
5736
                else:
6217
 
                    self.outf.write(gettext("    <no hooks installed>\n"))
6218
 
 
6219
 
 
6220
 
class cmd_remove_branch(Command):
6221
 
    __doc__ = """Remove a branch.
6222
 
 
6223
 
    This will remove the branch from the specified location but 
6224
 
    will keep any working tree or repository in place.
6225
 
 
6226
 
    :Examples:
6227
 
 
6228
 
      Remove the branch at repo/trunk::
6229
 
 
6230
 
        bzr remove-branch repo/trunk
6231
 
 
6232
 
    """
6233
 
 
6234
 
    takes_args = ["location?"]
6235
 
 
6236
 
    aliases = ["rmbranch"]
6237
 
 
6238
 
    def run(self, location=None):
6239
 
        if location is None:
6240
 
            location = "."
6241
 
        branch = Branch.open_containing(location)[0]
6242
 
        branch.bzrdir.destroy_branch()
 
5737
                    self.outf.write("    <no hooks installed>\n")
6243
5738
 
6244
5739
 
6245
5740
class cmd_shelve(Command):
6246
 
    __doc__ = """Temporarily set aside some changes from the current tree.
 
5741
    """Temporarily set aside some changes from the current tree.
6247
5742
 
6248
5743
    Shelve allows you to temporarily put changes you've made "on the shelf",
6249
5744
    ie. out of the way, until a later time when you can bring them back from
6265
5760
 
6266
5761
    You can put multiple items on the shelf, and by default, 'unshelve' will
6267
5762
    restore the most recently shelved changes.
6268
 
 
6269
 
    For complicated changes, it is possible to edit the changes in a separate
6270
 
    editor program to decide what the file remaining in the working copy
6271
 
    should look like.  To do this, add the configuration option
6272
 
 
6273
 
        change_editor = PROGRAM @new_path @old_path
6274
 
 
6275
 
    where @new_path is replaced with the path of the new version of the 
6276
 
    file and @old_path is replaced with the path of the old version of 
6277
 
    the file.  The PROGRAM should save the new file with the desired 
6278
 
    contents of the file in the working tree.
6279
 
        
6280
5763
    """
6281
5764
 
6282
5765
    takes_args = ['file*']
6283
5766
 
6284
5767
    takes_options = [
6285
 
        'directory',
6286
5768
        'revision',
6287
5769
        Option('all', help='Shelve all changes.'),
6288
5770
        'message',
6294
5776
        Option('destroy',
6295
5777
               help='Destroy removed changes instead of shelving them.'),
6296
5778
    ]
6297
 
    _see_also = ['unshelve', 'configuration']
 
5779
    _see_also = ['unshelve']
6298
5780
 
6299
5781
    def run(self, revision=None, all=False, file_list=None, message=None,
6300
 
            writer=None, list=False, destroy=False, directory=None):
 
5782
            writer=None, list=False, destroy=False):
6301
5783
        if list:
6302
 
            return self.run_for_list(directory=directory)
 
5784
            return self.run_for_list()
6303
5785
        from bzrlib.shelf_ui import Shelver
6304
5786
        if writer is None:
6305
5787
            writer = bzrlib.option.diff_writer_registry.get()
6306
5788
        try:
6307
5789
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6308
 
                file_list, message, destroy=destroy, directory=directory)
 
5790
                file_list, message, destroy=destroy)
6309
5791
            try:
6310
5792
                shelver.run()
6311
5793
            finally:
6313
5795
        except errors.UserAbort:
6314
5796
            return 0
6315
5797
 
6316
 
    def run_for_list(self, directory=None):
6317
 
        if directory is None:
6318
 
            directory = u'.'
6319
 
        tree = WorkingTree.open_containing(directory)[0]
6320
 
        self.add_cleanup(tree.lock_read().unlock)
6321
 
        manager = tree.get_shelf_manager()
6322
 
        shelves = manager.active_shelves()
6323
 
        if len(shelves) == 0:
6324
 
            note(gettext('No shelved changes.'))
6325
 
            return 0
6326
 
        for shelf_id in reversed(shelves):
6327
 
            message = manager.get_metadata(shelf_id).get('message')
6328
 
            if message is None:
6329
 
                message = '<no message>'
6330
 
            self.outf.write('%3d: %s\n' % (shelf_id, message))
6331
 
        return 1
 
5798
    def run_for_list(self):
 
5799
        tree = WorkingTree.open_containing('.')[0]
 
5800
        tree.lock_read()
 
5801
        try:
 
5802
            manager = tree.get_shelf_manager()
 
5803
            shelves = manager.active_shelves()
 
5804
            if len(shelves) == 0:
 
5805
                note('No shelved changes.')
 
5806
                return 0
 
5807
            for shelf_id in reversed(shelves):
 
5808
                message = manager.get_metadata(shelf_id).get('message')
 
5809
                if message is None:
 
5810
                    message = '<no message>'
 
5811
                self.outf.write('%3d: %s\n' % (shelf_id, message))
 
5812
            return 1
 
5813
        finally:
 
5814
            tree.unlock()
6332
5815
 
6333
5816
 
6334
5817
class cmd_unshelve(Command):
6335
 
    __doc__ = """Restore shelved changes.
 
5818
    """Restore shelved changes.
6336
5819
 
6337
5820
    By default, the most recently shelved changes are restored. However if you
6338
5821
    specify a shelf by id those changes will be restored instead.  This works
6341
5824
 
6342
5825
    takes_args = ['shelf_id?']
6343
5826
    takes_options = [
6344
 
        'directory',
6345
5827
        RegistryOption.from_kwargs(
6346
5828
            'action', help="The action to perform.",
6347
5829
            enum_switch=False, value_switches=True,
6348
5830
            apply="Apply changes and remove from the shelf.",
6349
5831
            dry_run="Show changes, but do not apply or remove them.",
6350
 
            preview="Instead of unshelving the changes, show the diff that "
6351
 
                    "would result from unshelving.",
6352
5832
            delete_only="Delete changes without applying them.",
6353
5833
            keep="Apply changes but don't delete them.",
6354
5834
        )
6355
5835
    ]
6356
5836
    _see_also = ['shelve']
6357
5837
 
6358
 
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
5838
    def run(self, shelf_id=None, action='apply'):
6359
5839
        from bzrlib.shelf_ui import Unshelver
6360
 
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
5840
        unshelver = Unshelver.from_args(shelf_id, action)
6361
5841
        try:
6362
5842
            unshelver.run()
6363
5843
        finally:
6365
5845
 
6366
5846
 
6367
5847
class cmd_clean_tree(Command):
6368
 
    __doc__ = """Remove unwanted files from working tree.
 
5848
    """Remove unwanted files from working tree.
6369
5849
 
6370
5850
    By default, only unknown files, not ignored files, are deleted.  Versioned
6371
5851
    files are never deleted.
6379
5859
 
6380
5860
    To check what clean-tree will do, use --dry-run.
6381
5861
    """
6382
 
    takes_options = ['directory',
6383
 
                     Option('ignored', help='Delete all ignored files.'),
6384
 
                     Option('detritus', help='Delete conflict files, merge and revert'
 
5862
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5863
                     Option('detritus', help='Delete conflict files, merge'
6385
5864
                            ' backups, and failed selftest dirs.'),
6386
5865
                     Option('unknown',
6387
5866
                            help='Delete files unknown to bzr (default).'),
6389
5868
                            ' deleting them.'),
6390
5869
                     Option('force', help='Do not prompt before deleting.')]
6391
5870
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6392
 
            force=False, directory=u'.'):
 
5871
            force=False):
6393
5872
        from bzrlib.clean_tree import clean_tree
6394
5873
        if not (unknown or ignored or detritus):
6395
5874
            unknown = True
6396
5875
        if dry_run:
6397
5876
            force = True
6398
 
        clean_tree(directory, unknown=unknown, ignored=ignored,
6399
 
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5877
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5878
                   dry_run=dry_run, no_prompt=force)
6400
5879
 
6401
5880
 
6402
5881
class cmd_reference(Command):
6403
 
    __doc__ = """list, view and set branch locations for nested trees.
 
5882
    """list, view and set branch locations for nested trees.
6404
5883
 
6405
5884
    If no arguments are provided, lists the branch locations for nested trees.
6406
5885
    If one argument is provided, display the branch location for that tree.
6446
5925
            self.outf.write('%s %s\n' % (path, location))
6447
5926
 
6448
5927
 
6449
 
class cmd_export_pot(Command):
6450
 
    __doc__ = """Export command helps and error messages in po format."""
6451
 
 
6452
 
    hidden = True
6453
 
 
6454
 
    def run(self):
6455
 
        from bzrlib.export_pot import export_pot
6456
 
        export_pot(self.outf)
6457
 
 
6458
 
 
6459
 
def _register_lazy_builtins():
6460
 
    # register lazy builtins from other modules; called at startup and should
6461
 
    # be only called once.
6462
 
    for (name, aliases, module_name) in [
6463
 
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6464
 
        ('cmd_config', [], 'bzrlib.config'),
6465
 
        ('cmd_dpush', [], 'bzrlib.foreign'),
6466
 
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6467
 
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6468
 
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6469
 
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6470
 
        ('cmd_verify_signatures', [],
6471
 
                                        'bzrlib.commit_signature_commands'),
6472
 
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6473
 
        ]:
6474
 
        builtin_command_registry.register_lazy(name, aliases, module_name)
 
5928
# these get imported and then picked up by the scan for cmd_*
 
5929
# TODO: Some more consistent way to split command definitions across files;
 
5930
# we do need to load at least some information about them to know of
 
5931
# aliases.  ideally we would avoid loading the implementation until the
 
5932
# details were needed.
 
5933
from bzrlib.cmd_version_info import cmd_version_info
 
5934
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
5935
from bzrlib.bundle.commands import (
 
5936
    cmd_bundle_info,
 
5937
    )
 
5938
from bzrlib.foreign import cmd_dpush
 
5939
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
5940
from bzrlib.weave_commands import cmd_versionedfile_list, \
 
5941
        cmd_weave_plan_merge, cmd_weave_merge_text