~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Martin von Gagern
  • Date: 2010-04-22 06:25:26 UTC
  • mfrom: (0.27.39 trunk)
  • mto: This revision was merged to the branch mainline in revision 5240.
  • Revision ID: martin.vgagern@gmx.net-20100422062526-4lyy2yoor932u80w
Join bzr-bash-completion plugin into core bzr tree.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
72
73
    _parse_revision_str,
73
74
    )
74
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
75
 
from bzrlib import (
76
 
    symbol_versioning,
77
 
    )
78
 
 
79
 
 
80
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
 
76
 
 
77
 
81
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
82
79
    apply_view=True):
83
 
    return internal_tree_files(file_list, default_branch, canonicalize,
84
 
        apply_view)
 
80
    try:
 
81
        return internal_tree_files(file_list, default_branch, canonicalize,
 
82
            apply_view)
 
83
    except errors.FileInWrongBranch, e:
 
84
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
 
85
                                     (e.path, file_list[0]))
85
86
 
86
87
 
87
88
def tree_files_for_add(file_list):
151
152
 
152
153
# XXX: Bad function name; should possibly also be a class method of
153
154
# WorkingTree rather than a function.
154
 
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
155
155
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
156
156
    apply_view=True):
157
157
    """Convert command-line paths to a WorkingTree and relative paths.
158
158
 
159
 
    Deprecated: use WorkingTree.open_containing_paths instead.
160
 
 
161
159
    This is typically used for command-line processors that take one or
162
160
    more filenames, and infer the workingtree that contains them.
163
161
 
173
171
 
174
172
    :return: workingtree, [relative_paths]
175
173
    """
176
 
    return WorkingTree.open_containing_paths(
177
 
        file_list, default_directory='.',
178
 
        canonicalize=True,
179
 
        apply_view=True)
 
174
    if file_list is None or len(file_list) == 0:
 
175
        tree = WorkingTree.open_containing(default_branch)[0]
 
176
        if tree.supports_views() and apply_view:
 
177
            view_files = tree.views.lookup_view()
 
178
            if view_files:
 
179
                file_list = view_files
 
180
                view_str = views.view_display_str(view_files)
 
181
                note("Ignoring files outside view. View is %s" % view_str)
 
182
        return tree, file_list
 
183
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
184
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
185
        apply_view=apply_view)
 
186
 
 
187
 
 
188
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
 
189
    """Convert file_list into a list of relpaths in tree.
 
190
 
 
191
    :param tree: A tree to operate on.
 
192
    :param file_list: A list of user provided paths or None.
 
193
    :param apply_view: if True and a view is set, apply it or check that
 
194
        specified files are within it
 
195
    :return: A list of relative paths.
 
196
    :raises errors.PathNotChild: When a provided path is in a different tree
 
197
        than tree.
 
198
    """
 
199
    if file_list is None:
 
200
        return None
 
201
    if tree.supports_views() and apply_view:
 
202
        view_files = tree.views.lookup_view()
 
203
    else:
 
204
        view_files = []
 
205
    new_list = []
 
206
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
 
207
    # doesn't - fix that up here before we enter the loop.
 
208
    if canonicalize:
 
209
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
 
210
    else:
 
211
        fixer = tree.relpath
 
212
    for filename in file_list:
 
213
        try:
 
214
            relpath = fixer(osutils.dereference_path(filename))
 
215
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
216
                raise errors.FileOutsideView(filename, view_files)
 
217
            new_list.append(relpath)
 
218
        except errors.PathNotChild:
 
219
            raise errors.FileInWrongBranch(tree.branch, filename)
 
220
    return new_list
180
221
 
181
222
 
182
223
def _get_view_info_for_change_reporter(tree):
191
232
    return view_info
192
233
 
193
234
 
194
 
def _open_directory_or_containing_tree_or_branch(filename, directory):
195
 
    """Open the tree or branch containing the specified file, unless
196
 
    the --directory option is used to specify a different branch."""
197
 
    if directory is not None:
198
 
        return (None, Branch.open(directory), filename)
199
 
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
200
 
 
201
 
 
202
235
# TODO: Make sure no commands unconditionally use the working directory as a
203
236
# branch.  If a filename argument is used, the first of them should be used to
204
237
# specify the branch.  (Perhaps this can be factored out into some kind of
206
239
# opens the branch?)
207
240
 
208
241
class cmd_status(Command):
209
 
    __doc__ = """Display status summary.
 
242
    """Display status summary.
210
243
 
211
244
    This reports on versioned and unknown files, reporting them
212
245
    grouped by state.  Possible states are:
232
265
    unknown
233
266
        Not versioned and not matching an ignore pattern.
234
267
 
235
 
    Additionally for directories, symlinks and files with a changed
236
 
    executable bit, Bazaar indicates their type using a trailing
237
 
    character: '/', '@' or '*' respectively. These decorations can be
238
 
    disabled using the '--no-classify' option.
 
268
    Additionally for directories, symlinks and files with an executable
 
269
    bit, Bazaar indicates their type using a trailing character: '/', '@'
 
270
    or '*' respectively.
239
271
 
240
272
    To see ignored files use 'bzr ignored'.  For details on the
241
273
    changes to file texts, use 'bzr diff'.
254
286
    To skip the display of pending merge information altogether, use
255
287
    the no-pending option or specify a file/directory.
256
288
 
257
 
    To compare the working directory to a specific revision, pass a
258
 
    single revision to the revision argument.
259
 
 
260
 
    To see which files have changed in a specific revision, or between
261
 
    two revisions, pass a revision range to the revision argument.
262
 
    This will produce the same results as calling 'bzr diff --summarize'.
 
289
    If a revision argument is given, the status is calculated against
 
290
    that revision, or between two revisions if two are provided.
263
291
    """
264
292
 
265
293
    # TODO: --no-recurse, --recurse options
272
300
                            short_name='V'),
273
301
                     Option('no-pending', help='Don\'t show pending merges.',
274
302
                           ),
275
 
                     Option('no-classify',
276
 
                            help='Do not mark object type using indicator.',
277
 
                           ),
278
303
                     ]
279
304
    aliases = ['st', 'stat']
280
305
 
283
308
 
284
309
    @display_command
285
310
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
286
 
            versioned=False, no_pending=False, verbose=False,
287
 
            no_classify=False):
 
311
            versioned=False, no_pending=False, verbose=False):
288
312
        from bzrlib.status import show_tree_status
289
313
 
290
314
        if revision and len(revision) > 2:
291
315
            raise errors.BzrCommandError('bzr status --revision takes exactly'
292
316
                                         ' one or two revision specifiers')
293
317
 
294
 
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
318
        tree, relfile_list = tree_files(file_list)
295
319
        # Avoid asking for specific files when that is not needed.
296
320
        if relfile_list == ['']:
297
321
            relfile_list = None
304
328
        show_tree_status(tree, show_ids=show_ids,
305
329
                         specific_files=relfile_list, revision=revision,
306
330
                         to_file=self.outf, short=short, versioned=versioned,
307
 
                         show_pending=(not no_pending), verbose=verbose,
308
 
                         classify=not no_classify)
 
331
                         show_pending=(not no_pending), verbose=verbose)
309
332
 
310
333
 
311
334
class cmd_cat_revision(Command):
312
 
    __doc__ = """Write out metadata for a revision.
 
335
    """Write out metadata for a revision.
313
336
 
314
337
    The revision to print can either be specified by a specific
315
338
    revision identifier, or you can use --revision.
317
340
 
318
341
    hidden = True
319
342
    takes_args = ['revision_id?']
320
 
    takes_options = ['directory', 'revision']
 
343
    takes_options = ['revision']
321
344
    # cat-revision is more for frontends so should be exact
322
345
    encoding = 'strict'
323
346
 
330
353
        self.outf.write(revtext.decode('utf-8'))
331
354
 
332
355
    @display_command
333
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
356
    def run(self, revision_id=None, revision=None):
334
357
        if revision_id is not None and revision is not None:
335
358
            raise errors.BzrCommandError('You can only supply one of'
336
359
                                         ' revision_id or --revision')
337
360
        if revision_id is None and revision is None:
338
361
            raise errors.BzrCommandError('You must supply either'
339
362
                                         ' --revision or a revision_id')
340
 
 
341
 
        b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
 
363
        b = WorkingTree.open_containing(u'.')[0].branch
342
364
 
343
365
        revisions = b.repository.revisions
344
366
        if revisions is None:
368
390
        
369
391
 
370
392
class cmd_dump_btree(Command):
371
 
    __doc__ = """Dump the contents of a btree index file to stdout.
 
393
    """Dump the contents of a btree index file to stdout.
372
394
 
373
395
    PATH is a btree index file, it can be any URL. This includes things like
374
396
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
422
444
                self.outf.write(page_bytes[:header_end])
423
445
                page_bytes = data
424
446
            self.outf.write('\nPage %d\n' % (page_idx,))
425
 
            if len(page_bytes) == 0:
426
 
                self.outf.write('(empty)\n');
427
 
            else:
428
 
                decomp_bytes = zlib.decompress(page_bytes)
429
 
                self.outf.write(decomp_bytes)
430
 
                self.outf.write('\n')
 
447
            decomp_bytes = zlib.decompress(page_bytes)
 
448
            self.outf.write(decomp_bytes)
 
449
            self.outf.write('\n')
431
450
 
432
451
    def _dump_entries(self, trans, basename):
433
452
        try:
452
471
 
453
472
 
454
473
class cmd_remove_tree(Command):
455
 
    __doc__ = """Remove the working tree from a given branch/checkout.
 
474
    """Remove the working tree from a given branch/checkout.
456
475
 
457
476
    Since a lightweight checkout is little more than a working tree
458
477
    this will refuse to run against one.
464
483
    takes_options = [
465
484
        Option('force',
466
485
               help='Remove the working tree even if it has '
467
 
                    'uncommitted or shelved changes.'),
 
486
                    'uncommitted changes.'),
468
487
        ]
469
488
 
470
489
    def run(self, location_list, force=False):
484
503
            if not force:
485
504
                if (working.has_changes()):
486
505
                    raise errors.UncommittedChanges(working)
487
 
                if working.get_shelf_manager().last_shelf() is not None:
488
 
                    raise errors.ShelvedChanges(working)
489
506
 
490
 
            if working.user_url != working.branch.user_url:
 
507
            working_path = working.bzrdir.root_transport.base
 
508
            branch_path = working.branch.bzrdir.root_transport.base
 
509
            if working_path != branch_path:
491
510
                raise errors.BzrCommandError("You cannot remove the working tree"
492
511
                                             " from a lightweight checkout")
493
512
 
494
513
            d.destroy_workingtree()
495
514
 
496
515
 
497
 
class cmd_repair_workingtree(Command):
498
 
    __doc__ = """Reset the working tree state file.
499
 
 
500
 
    This is not meant to be used normally, but more as a way to recover from
501
 
    filesystem corruption, etc. This rebuilds the working inventory back to a
502
 
    'known good' state. Any new modifications (adding a file, renaming, etc)
503
 
    will be lost, though modified files will still be detected as such.
504
 
 
505
 
    Most users will want something more like "bzr revert" or "bzr update"
506
 
    unless the state file has become corrupted.
507
 
 
508
 
    By default this attempts to recover the current state by looking at the
509
 
    headers of the state file. If the state file is too corrupted to even do
510
 
    that, you can supply --revision to force the state of the tree.
511
 
    """
512
 
 
513
 
    takes_options = ['revision', 'directory',
514
 
        Option('force',
515
 
               help='Reset the tree even if it doesn\'t appear to be'
516
 
                    ' corrupted.'),
517
 
    ]
518
 
    hidden = True
519
 
 
520
 
    def run(self, revision=None, directory='.', force=False):
521
 
        tree, _ = WorkingTree.open_containing(directory)
522
 
        self.add_cleanup(tree.lock_tree_write().unlock)
523
 
        if not force:
524
 
            try:
525
 
                tree.check_state()
526
 
            except errors.BzrError:
527
 
                pass # There seems to be a real error here, so we'll reset
528
 
            else:
529
 
                # Refuse
530
 
                raise errors.BzrCommandError(
531
 
                    'The tree does not appear to be corrupt. You probably'
532
 
                    ' want "bzr revert" instead. Use "--force" if you are'
533
 
                    ' sure you want to reset the working tree.')
534
 
        if revision is None:
535
 
            revision_ids = None
536
 
        else:
537
 
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
538
 
        try:
539
 
            tree.reset_state(revision_ids)
540
 
        except errors.BzrError, e:
541
 
            if revision_ids is None:
542
 
                extra = (', the header appears corrupt, try passing -r -1'
543
 
                         ' to set the state to the last commit')
544
 
            else:
545
 
                extra = ''
546
 
            raise errors.BzrCommandError('failed to reset the tree state'
547
 
                                         + extra)
548
 
 
549
 
 
550
516
class cmd_revno(Command):
551
 
    __doc__ = """Show current revision number.
 
517
    """Show current revision number.
552
518
 
553
519
    This is equal to the number of revisions on this branch.
554
520
    """
564
530
        if tree:
565
531
            try:
566
532
                wt = WorkingTree.open_containing(location)[0]
567
 
                self.add_cleanup(wt.lock_read().unlock)
 
533
                wt.lock_read()
568
534
            except (errors.NoWorkingTree, errors.NotLocalUrl):
569
535
                raise errors.NoWorkingTree(location)
 
536
            self.add_cleanup(wt.unlock)
570
537
            revid = wt.last_revision()
571
538
            try:
572
539
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
575
542
            revno = ".".join(str(n) for n in revno_t)
576
543
        else:
577
544
            b = Branch.open_containing(location)[0]
578
 
            self.add_cleanup(b.lock_read().unlock)
 
545
            b.lock_read()
 
546
            self.add_cleanup(b.unlock)
579
547
            revno = b.revno()
580
548
        self.cleanup_now()
581
549
        self.outf.write(str(revno) + '\n')
582
550
 
583
551
 
584
552
class cmd_revision_info(Command):
585
 
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
553
    """Show revision number and revision id for a given revision identifier.
586
554
    """
587
555
    hidden = True
588
556
    takes_args = ['revision_info*']
589
557
    takes_options = [
590
558
        'revision',
591
 
        custom_help('directory',
 
559
        Option('directory',
592
560
            help='Branch to examine, '
593
 
                 'rather than the one containing the working directory.'),
 
561
                 'rather than the one containing the working directory.',
 
562
            short_name='d',
 
563
            type=unicode,
 
564
            ),
594
565
        Option('tree', help='Show revno of working tree'),
595
566
        ]
596
567
 
601
572
        try:
602
573
            wt = WorkingTree.open_containing(directory)[0]
603
574
            b = wt.branch
604
 
            self.add_cleanup(wt.lock_read().unlock)
 
575
            wt.lock_read()
 
576
            self.add_cleanup(wt.unlock)
605
577
        except (errors.NoWorkingTree, errors.NotLocalUrl):
606
578
            wt = None
607
579
            b = Branch.open_containing(directory)[0]
608
 
            self.add_cleanup(b.lock_read().unlock)
 
580
            b.lock_read()
 
581
            self.add_cleanup(b.unlock)
609
582
        revision_ids = []
610
583
        if revision is not None:
611
584
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
639
612
 
640
613
 
641
614
class cmd_add(Command):
642
 
    __doc__ = """Add specified files or directories.
 
615
    """Add specified files or directories.
643
616
 
644
617
    In non-recursive mode, all the named items are added, regardless
645
618
    of whether they were previously ignored.  A warning is given if
710
683
                should_print=(not is_quiet()))
711
684
 
712
685
        if base_tree:
713
 
            self.add_cleanup(base_tree.lock_read().unlock)
 
686
            base_tree.lock_read()
 
687
            self.add_cleanup(base_tree.unlock)
714
688
        tree, file_list = tree_files_for_add(file_list)
715
689
        added, ignored = tree.smart_add(file_list, not
716
690
            no_recurse, action=action, save=not dry_run)
724
698
 
725
699
 
726
700
class cmd_mkdir(Command):
727
 
    __doc__ = """Create a new versioned directory.
 
701
    """Create a new versioned directory.
728
702
 
729
703
    This is equivalent to creating the directory and then adding it.
730
704
    """
746
720
 
747
721
 
748
722
class cmd_relpath(Command):
749
 
    __doc__ = """Show path of a file relative to root"""
 
723
    """Show path of a file relative to root"""
750
724
 
751
725
    takes_args = ['filename']
752
726
    hidden = True
761
735
 
762
736
 
763
737
class cmd_inventory(Command):
764
 
    __doc__ = """Show inventory of the current working copy or a revision.
 
738
    """Show inventory of the current working copy or a revision.
765
739
 
766
740
    It is possible to limit the output to a particular entry
767
741
    type using the --kind option.  For example: --kind file.
787
761
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
788
762
 
789
763
        revision = _get_one_revision('inventory', revision)
790
 
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
791
 
        self.add_cleanup(work_tree.lock_read().unlock)
 
764
        work_tree, file_list = tree_files(file_list)
 
765
        work_tree.lock_read()
 
766
        self.add_cleanup(work_tree.unlock)
792
767
        if revision is not None:
793
768
            tree = revision.as_tree(work_tree.branch)
794
769
 
795
770
            extra_trees = [work_tree]
796
 
            self.add_cleanup(tree.lock_read().unlock)
 
771
            tree.lock_read()
 
772
            self.add_cleanup(tree.unlock)
797
773
        else:
798
774
            tree = work_tree
799
775
            extra_trees = []
803
779
                                      require_versioned=True)
804
780
            # find_ids_across_trees may include some paths that don't
805
781
            # exist in 'tree'.
806
 
            entries = sorted(
807
 
                (tree.id2path(file_id), tree.inventory[file_id])
808
 
                for file_id in file_ids if tree.has_id(file_id))
 
782
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
783
                             for file_id in file_ids if file_id in tree)
809
784
        else:
810
785
            entries = tree.inventory.entries()
811
786
 
821
796
 
822
797
 
823
798
class cmd_mv(Command):
824
 
    __doc__ = """Move or rename a file.
 
799
    """Move or rename a file.
825
800
 
826
801
    :Usage:
827
802
        bzr mv OLDNAME NEWNAME
859
834
            names_list = []
860
835
        if len(names_list) < 2:
861
836
            raise errors.BzrCommandError("missing file argument")
862
 
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
863
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
837
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
838
        tree.lock_tree_write()
 
839
        self.add_cleanup(tree.unlock)
864
840
        self._run(tree, names_list, rel_names, after)
865
841
 
866
842
    def run_auto(self, names_list, after, dry_run):
870
846
        if after:
871
847
            raise errors.BzrCommandError('--after cannot be specified with'
872
848
                                         ' --auto.')
873
 
        work_tree, file_list = WorkingTree.open_containing_paths(
874
 
            names_list, default_directory='.')
875
 
        self.add_cleanup(work_tree.lock_tree_write().unlock)
 
849
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
850
        work_tree.lock_tree_write()
 
851
        self.add_cleanup(work_tree.unlock)
876
852
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
877
853
 
878
854
    def _run(self, tree, names_list, rel_names, after):
957
933
 
958
934
 
959
935
class cmd_pull(Command):
960
 
    __doc__ = """Turn this branch into a mirror of another branch.
 
936
    """Turn this branch into a mirror of another branch.
961
937
 
962
938
    By default, this command only works on branches that have not diverged.
963
939
    Branches are considered diverged if the destination branch's most recent 
972
948
    match the remote one, use pull --overwrite. This will work even if the two
973
949
    branches have diverged.
974
950
 
975
 
    If there is no default location set, the first pull will set it (use
976
 
    --no-remember to avoid settting it). After that, you can omit the
977
 
    location to use the default.  To change the default, use --remember. The
978
 
    value will only be saved if the remote location can be accessed.
 
951
    If there is no default location set, the first pull will set it.  After
 
952
    that, you can omit the location to use the default.  To change the
 
953
    default, use --remember. The value will only be saved if the remote
 
954
    location can be accessed.
979
955
 
980
956
    Note: The location can be specified either in the form of a branch,
981
957
    or in the form of a path to a file containing a merge directive generated
986
962
    takes_options = ['remember', 'overwrite', 'revision',
987
963
        custom_help('verbose',
988
964
            help='Show logs of pulled revisions.'),
989
 
        custom_help('directory',
 
965
        Option('directory',
990
966
            help='Branch to pull into, '
991
 
                 'rather than the one containing the working directory.'),
 
967
                 'rather than the one containing the working directory.',
 
968
            short_name='d',
 
969
            type=unicode,
 
970
            ),
992
971
        Option('local',
993
972
            help="Perform a local pull in a bound "
994
973
                 "branch.  Local pulls are not applied to "
995
974
                 "the master branch."
996
975
            ),
997
 
        Option('show-base',
998
 
            help="Show base revision text in conflicts.")
999
976
        ]
1000
977
    takes_args = ['location?']
1001
978
    encoding_type = 'replace'
1002
979
 
1003
 
    def run(self, location=None, remember=None, overwrite=False,
 
980
    def run(self, location=None, remember=False, overwrite=False,
1004
981
            revision=None, verbose=False,
1005
 
            directory=None, local=False,
1006
 
            show_base=False):
 
982
            directory=None, local=False):
1007
983
        # FIXME: too much stuff is in the command class
1008
984
        revision_id = None
1009
985
        mergeable = None
1012
988
        try:
1013
989
            tree_to = WorkingTree.open_containing(directory)[0]
1014
990
            branch_to = tree_to.branch
1015
 
            self.add_cleanup(tree_to.lock_write().unlock)
1016
991
        except errors.NoWorkingTree:
1017
992
            tree_to = None
1018
993
            branch_to = Branch.open_containing(directory)[0]
1019
 
            self.add_cleanup(branch_to.lock_write().unlock)
1020
 
 
1021
 
        if tree_to is None and show_base:
1022
 
            raise errors.BzrCommandError("Need working tree for --show-base.")
1023
 
 
 
994
        
1024
995
        if local and not branch_to.get_bound_location():
1025
996
            raise errors.LocalRequiresBoundBranch()
1026
997
 
1056
1027
        else:
1057
1028
            branch_from = Branch.open(location,
1058
1029
                possible_transports=possible_transports)
1059
 
            self.add_cleanup(branch_from.lock_read().unlock)
1060
 
            # Remembers if asked explicitly or no previous location is set
1061
 
            if (remember
1062
 
                or (remember is None and branch_to.get_parent() is None)):
 
1030
 
 
1031
            if branch_to.get_parent() is None or remember:
1063
1032
                branch_to.set_parent(branch_from.base)
1064
1033
 
 
1034
        if branch_from is not branch_to:
 
1035
            branch_from.lock_read()
 
1036
            self.add_cleanup(branch_from.unlock)
1065
1037
        if revision is not None:
1066
1038
            revision_id = revision.as_revision_id(branch_from)
1067
1039
 
 
1040
        branch_to.lock_write()
 
1041
        self.add_cleanup(branch_to.unlock)
1068
1042
        if tree_to is not None:
1069
1043
            view_info = _get_view_info_for_change_reporter(tree_to)
1070
1044
            change_reporter = delta._ChangeReporter(
1072
1046
                view_info=view_info)
1073
1047
            result = tree_to.pull(
1074
1048
                branch_from, overwrite, revision_id, change_reporter,
1075
 
                possible_transports=possible_transports, local=local,
1076
 
                show_base=show_base)
 
1049
                possible_transports=possible_transports, local=local)
1077
1050
        else:
1078
1051
            result = branch_to.pull(
1079
1052
                branch_from, overwrite, revision_id, local=local)
1083
1056
            log.show_branch_change(
1084
1057
                branch_to, self.outf, result.old_revno,
1085
1058
                result.old_revid)
1086
 
        if getattr(result, 'tag_conflicts', None):
1087
 
            return 1
1088
 
        else:
1089
 
            return 0
1090
1059
 
1091
1060
 
1092
1061
class cmd_push(Command):
1093
 
    __doc__ = """Update a mirror of this branch.
 
1062
    """Update a mirror of this branch.
1094
1063
 
1095
1064
    The target branch will not have its working tree populated because this
1096
1065
    is both expensive, and is not supported on remote file systems.
1109
1078
    do a merge (see bzr help merge) from the other branch, and commit that.
1110
1079
    After that you will be able to do a push without '--overwrite'.
1111
1080
 
1112
 
    If there is no default push location set, the first push will set it (use
1113
 
    --no-remember to avoid settting it).  After that, you can omit the
1114
 
    location to use the default.  To change the default, use --remember. The
1115
 
    value will only be saved if the remote location can be accessed.
 
1081
    If there is no default push location set, the first push will set it.
 
1082
    After that, you can omit the location to use the default.  To change the
 
1083
    default, use --remember. The value will only be saved if the remote
 
1084
    location can be accessed.
1116
1085
    """
1117
1086
 
1118
1087
    _see_also = ['pull', 'update', 'working-trees']
1120
1089
        Option('create-prefix',
1121
1090
               help='Create the path leading up to the branch '
1122
1091
                    'if it does not already exist.'),
1123
 
        custom_help('directory',
 
1092
        Option('directory',
1124
1093
            help='Branch to push from, '
1125
 
                 'rather than the one containing the working directory.'),
 
1094
                 'rather than the one containing the working directory.',
 
1095
            short_name='d',
 
1096
            type=unicode,
 
1097
            ),
1126
1098
        Option('use-existing-dir',
1127
1099
               help='By default push will fail if the target'
1128
1100
                    ' directory exists, but does not already'
1139
1111
        Option('strict',
1140
1112
               help='Refuse to push if there are uncommitted changes in'
1141
1113
               ' the working tree, --no-strict disables the check.'),
1142
 
        Option('no-tree',
1143
 
               help="Don't populate the working tree, even for protocols"
1144
 
               " that support it."),
1145
1114
        ]
1146
1115
    takes_args = ['location?']
1147
1116
    encoding_type = 'replace'
1148
1117
 
1149
 
    def run(self, location=None, remember=None, overwrite=False,
 
1118
    def run(self, location=None, remember=False, overwrite=False,
1150
1119
        create_prefix=False, verbose=False, revision=None,
1151
1120
        use_existing_dir=False, directory=None, stacked_on=None,
1152
 
        stacked=False, strict=None, no_tree=False):
 
1121
        stacked=False, strict=None):
1153
1122
        from bzrlib.push import _show_push_branch
1154
1123
 
1155
1124
        if directory is None:
1157
1126
        # Get the source branch
1158
1127
        (tree, br_from,
1159
1128
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1129
        if strict is None:
 
1130
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
 
1131
        if strict is None: strict = True # default value
1160
1132
        # Get the tip's revision_id
1161
1133
        revision = _get_one_revision('push', revision)
1162
1134
        if revision is not None:
1163
1135
            revision_id = revision.in_history(br_from).rev_id
1164
1136
        else:
1165
1137
            revision_id = None
1166
 
        if tree is not None and revision_id is None:
1167
 
            tree.check_changed_or_out_of_date(
1168
 
                strict, 'push_strict',
1169
 
                more_error='Use --no-strict to force the push.',
1170
 
                more_warning='Uncommitted changes will not be pushed.')
 
1138
        if strict and tree is not None and revision_id is None:
 
1139
            if (tree.has_changes()):
 
1140
                raise errors.UncommittedChanges(
 
1141
                    tree, more='Use --no-strict to force the push.')
 
1142
            if tree.last_revision() != tree.branch.last_revision():
 
1143
                # The tree has lost sync with its branch, there is little
 
1144
                # chance that the user is aware of it but he can still force
 
1145
                # the push with --no-strict
 
1146
                raise errors.OutOfDateTree(
 
1147
                    tree, more='Use --no-strict to force the push.')
 
1148
 
1171
1149
        # Get the stacked_on branch, if any
1172
1150
        if stacked_on is not None:
1173
1151
            stacked_on = urlutils.normalize_url(stacked_on)
1201
1179
        _show_push_branch(br_from, revision_id, location, self.outf,
1202
1180
            verbose=verbose, overwrite=overwrite, remember=remember,
1203
1181
            stacked_on=stacked_on, create_prefix=create_prefix,
1204
 
            use_existing_dir=use_existing_dir, no_tree=no_tree)
 
1182
            use_existing_dir=use_existing_dir)
1205
1183
 
1206
1184
 
1207
1185
class cmd_branch(Command):
1208
 
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
1186
    """Create a new branch that is a copy of an existing branch.
1209
1187
 
1210
1188
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1211
1189
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1216
1194
 
1217
1195
    To retrieve the branch as of a particular revision, supply the --revision
1218
1196
    parameter, as in "branch foo/bar -r 5".
1219
 
 
1220
 
    The synonyms 'clone' and 'get' for this command are deprecated.
1221
1197
    """
1222
1198
 
1223
1199
    _see_also = ['checkout']
1224
1200
    takes_args = ['from_location', 'to_location?']
1225
 
    takes_options = ['revision',
1226
 
        Option('hardlink', help='Hard-link working tree files where possible.'),
1227
 
        Option('files-from', type=str,
1228
 
               help="Get file contents from this tree."),
 
1201
    takes_options = ['revision', Option('hardlink',
 
1202
        help='Hard-link working tree files where possible.'),
1229
1203
        Option('no-tree',
1230
1204
            help="Create a branch without a working-tree."),
1231
1205
        Option('switch',
1249
1223
 
1250
1224
    def run(self, from_location, to_location=None, revision=None,
1251
1225
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1252
 
            use_existing_dir=False, switch=False, bind=False,
1253
 
            files_from=None):
 
1226
            use_existing_dir=False, switch=False, bind=False):
1254
1227
        from bzrlib import switch as _mod_switch
1255
1228
        from bzrlib.tag import _merge_tags_if_possible
1256
 
        if self.invoked_as in ['get', 'clone']:
1257
 
            ui.ui_factory.show_user_warning(
1258
 
                'deprecated_command',
1259
 
                deprecated_name=self.invoked_as,
1260
 
                recommended_name='branch',
1261
 
                deprecated_in_version='2.4')
1262
1229
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1263
1230
            from_location)
1264
 
        if not (hardlink or files_from):
1265
 
            # accelerator_tree is usually slower because you have to read N
1266
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1267
 
            # explicitly request it
1268
 
            accelerator_tree = None
1269
 
        if files_from is not None and files_from != from_location:
1270
 
            accelerator_tree = WorkingTree.open(files_from)
1271
1231
        revision = _get_one_revision('branch', revision)
1272
 
        self.add_cleanup(br_from.lock_read().unlock)
 
1232
        br_from.lock_read()
 
1233
        self.add_cleanup(br_from.unlock)
1273
1234
        if revision is not None:
1274
1235
            revision_id = revision.as_revision_id(br_from)
1275
1236
        else:
1335
1296
 
1336
1297
 
1337
1298
class cmd_checkout(Command):
1338
 
    __doc__ = """Create a new checkout of an existing branch.
 
1299
    """Create a new checkout of an existing branch.
1339
1300
 
1340
1301
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1341
1302
    the branch found in '.'. This is useful if you have removed the working tree
1380
1341
            to_location = branch_location
1381
1342
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1382
1343
            branch_location)
1383
 
        if not (hardlink or files_from):
1384
 
            # accelerator_tree is usually slower because you have to read N
1385
 
            # files (no readahead, lots of seeks, etc), but allow the user to
1386
 
            # explicitly request it
1387
 
            accelerator_tree = None
1388
1344
        revision = _get_one_revision('checkout', revision)
1389
 
        if files_from is not None and files_from != branch_location:
 
1345
        if files_from is not None:
1390
1346
            accelerator_tree = WorkingTree.open(files_from)
1391
1347
        if revision is not None:
1392
1348
            revision_id = revision.as_revision_id(source)
1409
1365
 
1410
1366
 
1411
1367
class cmd_renames(Command):
1412
 
    __doc__ = """Show list of renamed files.
 
1368
    """Show list of renamed files.
1413
1369
    """
1414
1370
    # TODO: Option to show renames between two historical versions.
1415
1371
 
1420
1376
    @display_command
1421
1377
    def run(self, dir=u'.'):
1422
1378
        tree = WorkingTree.open_containing(dir)[0]
1423
 
        self.add_cleanup(tree.lock_read().unlock)
 
1379
        tree.lock_read()
 
1380
        self.add_cleanup(tree.unlock)
1424
1381
        new_inv = tree.inventory
1425
1382
        old_tree = tree.basis_tree()
1426
 
        self.add_cleanup(old_tree.lock_read().unlock)
 
1383
        old_tree.lock_read()
 
1384
        self.add_cleanup(old_tree.unlock)
1427
1385
        old_inv = old_tree.inventory
1428
1386
        renames = []
1429
1387
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1439
1397
 
1440
1398
 
1441
1399
class cmd_update(Command):
1442
 
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1400
    """Update a tree to have the latest code committed to its branch.
1443
1401
 
1444
1402
    This will perform a merge into the working tree, and may generate
1445
1403
    conflicts. If you have any local changes, you will still
1448
1406
    If you want to discard your local changes, you can just do a
1449
1407
    'bzr revert' instead of 'bzr commit' after the update.
1450
1408
 
1451
 
    If you want to restore a file that has been removed locally, use
1452
 
    'bzr revert' instead of 'bzr update'.
1453
 
 
1454
1409
    If the tree's branch is bound to a master branch, it will also update
1455
1410
    the branch from the master.
1456
1411
    """
1457
1412
 
1458
1413
    _see_also = ['pull', 'working-trees', 'status-flags']
1459
1414
    takes_args = ['dir?']
1460
 
    takes_options = ['revision',
1461
 
                     Option('show-base',
1462
 
                            help="Show base revision text in conflicts."),
1463
 
                     ]
 
1415
    takes_options = ['revision']
1464
1416
    aliases = ['up']
1465
1417
 
1466
 
    def run(self, dir='.', revision=None, show_base=None):
 
1418
    def run(self, dir='.', revision=None):
1467
1419
        if revision is not None and len(revision) != 1:
1468
1420
            raise errors.BzrCommandError(
1469
1421
                        "bzr update --revision takes exactly one revision")
1473
1425
        master = branch.get_master_branch(
1474
1426
            possible_transports=possible_transports)
1475
1427
        if master is not None:
 
1428
            tree.lock_write()
1476
1429
            branch_location = master.base
1477
 
            tree.lock_write()
1478
1430
        else:
 
1431
            tree.lock_tree_write()
1479
1432
            branch_location = tree.branch.base
1480
 
            tree.lock_tree_write()
1481
1433
        self.add_cleanup(tree.unlock)
1482
1434
        # get rid of the final '/' and be ready for display
1483
1435
        branch_location = urlutils.unescape_for_display(
1509
1461
                change_reporter,
1510
1462
                possible_transports=possible_transports,
1511
1463
                revision=revision_id,
1512
 
                old_tip=old_tip,
1513
 
                show_base=show_base)
 
1464
                old_tip=old_tip)
1514
1465
        except errors.NoSuchRevision, e:
1515
1466
            raise errors.BzrCommandError(
1516
1467
                                  "branch has no revision %s\n"
1521
1472
            _mod_revision.ensure_null(tree.last_revision()))
1522
1473
        note('Updated to revision %s of branch %s' %
1523
1474
             ('.'.join(map(str, revno)), branch_location))
1524
 
        parent_ids = tree.get_parent_ids()
1525
 
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
 
1475
        if tree.get_parent_ids()[1:] != existing_pending_merges:
1526
1476
            note('Your local commits will now show as pending merges with '
1527
1477
                 "'bzr status', and can be committed with 'bzr commit'.")
1528
1478
        if conflicts != 0:
1532
1482
 
1533
1483
 
1534
1484
class cmd_info(Command):
1535
 
    __doc__ = """Show information about a working tree, branch or repository.
 
1485
    """Show information about a working tree, branch or repository.
1536
1486
 
1537
1487
    This command will show all known locations and formats associated to the
1538
1488
    tree, branch or repository.
1576
1526
 
1577
1527
 
1578
1528
class cmd_remove(Command):
1579
 
    __doc__ = """Remove files or directories.
 
1529
    """Remove files or directories.
1580
1530
 
1581
 
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1582
 
    delete them if they can easily be recovered using revert otherwise they
1583
 
    will be backed up (adding an extention of the form .~#~). If no options or
1584
 
    parameters are given Bazaar will scan for files that are being tracked by
1585
 
    Bazaar but missing in your tree and stop tracking them for you.
 
1531
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1532
    them if they can easily be recovered using revert. If no options or
 
1533
    parameters are given bzr will scan for files that are being tracked by bzr
 
1534
    but missing in your tree and stop tracking them for you.
1586
1535
    """
1587
1536
    takes_args = ['file*']
1588
1537
    takes_options = ['verbose',
1590
1539
        RegistryOption.from_kwargs('file-deletion-strategy',
1591
1540
            'The file deletion mode to be used.',
1592
1541
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1593
 
            safe='Backup changed files (default).',
 
1542
            safe='Only delete files if they can be'
 
1543
                 ' safely recovered (default).',
1594
1544
            keep='Delete from bzr but leave the working copy.',
1595
 
            no_backup='Don\'t backup changed files.',
1596
1545
            force='Delete all the specified files, even if they can not be '
1597
 
                'recovered and even if they are non-empty directories. '
1598
 
                '(deprecated, use no-backup)')]
 
1546
                'recovered and even if they are non-empty directories.')]
1599
1547
    aliases = ['rm', 'del']
1600
1548
    encoding_type = 'replace'
1601
1549
 
1602
1550
    def run(self, file_list, verbose=False, new=False,
1603
1551
        file_deletion_strategy='safe'):
1604
 
        if file_deletion_strategy == 'force':
1605
 
            note("(The --force option is deprecated, rather use --no-backup "
1606
 
                "in future.)")
1607
 
            file_deletion_strategy = 'no-backup'
1608
 
 
1609
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1552
        tree, file_list = tree_files(file_list)
1610
1553
 
1611
1554
        if file_list is not None:
1612
1555
            file_list = [f for f in file_list]
1613
1556
 
1614
 
        self.add_cleanup(tree.lock_write().unlock)
 
1557
        tree.lock_write()
 
1558
        self.add_cleanup(tree.unlock)
1615
1559
        # Heuristics should probably all move into tree.remove_smart or
1616
1560
        # some such?
1617
1561
        if new:
1632
1576
            file_deletion_strategy = 'keep'
1633
1577
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1634
1578
            keep_files=file_deletion_strategy=='keep',
1635
 
            force=(file_deletion_strategy=='no-backup'))
 
1579
            force=file_deletion_strategy=='force')
1636
1580
 
1637
1581
 
1638
1582
class cmd_file_id(Command):
1639
 
    __doc__ = """Print file_id of a particular file or directory.
 
1583
    """Print file_id of a particular file or directory.
1640
1584
 
1641
1585
    The file_id is assigned when the file is first added and remains the
1642
1586
    same through all revisions where the file exists, even when it is
1658
1602
 
1659
1603
 
1660
1604
class cmd_file_path(Command):
1661
 
    __doc__ = """Print path of file_ids to a file or directory.
 
1605
    """Print path of file_ids to a file or directory.
1662
1606
 
1663
1607
    This prints one line for each directory down to the target,
1664
1608
    starting at the branch root.
1680
1624
 
1681
1625
 
1682
1626
class cmd_reconcile(Command):
1683
 
    __doc__ = """Reconcile bzr metadata in a branch.
 
1627
    """Reconcile bzr metadata in a branch.
1684
1628
 
1685
1629
    This can correct data mismatches that may have been caused by
1686
1630
    previous ghost operations or bzr upgrades. You should only
1700
1644
 
1701
1645
    _see_also = ['check']
1702
1646
    takes_args = ['branch?']
1703
 
    takes_options = [
1704
 
        Option('canonicalize-chks',
1705
 
               help='Make sure CHKs are in canonical form (repairs '
1706
 
                    'bug 522637).',
1707
 
               hidden=True),
1708
 
        ]
1709
1647
 
1710
 
    def run(self, branch=".", canonicalize_chks=False):
 
1648
    def run(self, branch="."):
1711
1649
        from bzrlib.reconcile import reconcile
1712
1650
        dir = bzrdir.BzrDir.open(branch)
1713
 
        reconcile(dir, canonicalize_chks=canonicalize_chks)
 
1651
        reconcile(dir)
1714
1652
 
1715
1653
 
1716
1654
class cmd_revision_history(Command):
1717
 
    __doc__ = """Display the list of revision ids on a branch."""
 
1655
    """Display the list of revision ids on a branch."""
1718
1656
 
1719
1657
    _see_also = ['log']
1720
1658
    takes_args = ['location?']
1730
1668
 
1731
1669
 
1732
1670
class cmd_ancestry(Command):
1733
 
    __doc__ = """List all revisions merged into this branch."""
 
1671
    """List all revisions merged into this branch."""
1734
1672
 
1735
1673
    _see_also = ['log', 'revision-history']
1736
1674
    takes_args = ['location?']
1748
1686
            b = wt.branch
1749
1687
            last_revision = wt.last_revision()
1750
1688
 
1751
 
        self.add_cleanup(b.repository.lock_read().unlock)
1752
 
        graph = b.repository.get_graph()
1753
 
        revisions = [revid for revid, parents in
1754
 
            graph.iter_ancestry([last_revision])]
1755
 
        for revision_id in reversed(revisions):
1756
 
            if _mod_revision.is_null(revision_id):
1757
 
                continue
 
1689
        revision_ids = b.repository.get_ancestry(last_revision)
 
1690
        revision_ids.pop(0)
 
1691
        for revision_id in revision_ids:
1758
1692
            self.outf.write(revision_id + '\n')
1759
1693
 
1760
1694
 
1761
1695
class cmd_init(Command):
1762
 
    __doc__ = """Make a directory into a versioned branch.
 
1696
    """Make a directory into a versioned branch.
1763
1697
 
1764
1698
    Use this to create an empty branch, or before importing an
1765
1699
    existing project.
1797
1731
                ),
1798
1732
         Option('append-revisions-only',
1799
1733
                help='Never change revnos or the existing log.'
1800
 
                '  Append revisions to it only.'),
1801
 
         Option('no-tree',
1802
 
                'Create a branch without a working tree.')
 
1734
                '  Append revisions to it only.')
1803
1735
         ]
1804
1736
    def run(self, location=None, format=None, append_revisions_only=False,
1805
 
            create_prefix=False, no_tree=False):
 
1737
            create_prefix=False):
1806
1738
        if format is None:
1807
1739
            format = bzrdir.format_registry.make_bzrdir('default')
1808
1740
        if location is None:
1831
1763
        except errors.NotBranchError:
1832
1764
            # really a NotBzrDir error...
1833
1765
            create_branch = bzrdir.BzrDir.create_branch_convenience
1834
 
            if no_tree:
1835
 
                force_new_tree = False
1836
 
            else:
1837
 
                force_new_tree = None
1838
1766
            branch = create_branch(to_transport.base, format=format,
1839
 
                                   possible_transports=[to_transport],
1840
 
                                   force_new_tree=force_new_tree)
 
1767
                                   possible_transports=[to_transport])
1841
1768
            a_bzrdir = branch.bzrdir
1842
1769
        else:
1843
1770
            from bzrlib.transport.local import LocalTransport
1847
1774
                        raise errors.BranchExistsWithoutWorkingTree(location)
1848
1775
                raise errors.AlreadyBranchError(location)
1849
1776
            branch = a_bzrdir.create_branch()
1850
 
            if not no_tree:
1851
 
                a_bzrdir.create_workingtree()
 
1777
            a_bzrdir.create_workingtree()
1852
1778
        if append_revisions_only:
1853
1779
            try:
1854
1780
                branch.set_append_revisions_only(True)
1876
1802
 
1877
1803
 
1878
1804
class cmd_init_repository(Command):
1879
 
    __doc__ = """Create a shared repository for branches to share storage space.
 
1805
    """Create a shared repository for branches to share storage space.
1880
1806
 
1881
1807
    New branches created under the repository directory will store their
1882
1808
    revisions in the repository, not in the branch directory.  For branches
1936
1862
 
1937
1863
 
1938
1864
class cmd_diff(Command):
1939
 
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1865
    """Show differences in the working tree, between revisions or branches.
1940
1866
 
1941
1867
    If no arguments are given, all changes for the current tree are listed.
1942
1868
    If files are given, only the changes in those files are listed.
1948
1874
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1949
1875
    produces patches suitable for "patch -p1".
1950
1876
 
1951
 
    Note that when using the -r argument with a range of revisions, the
1952
 
    differences are computed between the two specified revisions.  That
1953
 
    is, the command does not show the changes introduced by the first 
1954
 
    revision in the range.  This differs from the interpretation of 
1955
 
    revision ranges used by "bzr log" which includes the first revision
1956
 
    in the range.
1957
 
 
1958
1877
    :Exit values:
1959
1878
        1 - changed
1960
1879
        2 - unrepresentable changes
1978
1897
 
1979
1898
            bzr diff -r1..3 xxx
1980
1899
 
1981
 
        The changes introduced by revision 2 (equivalent to -r1..2)::
1982
 
 
1983
 
            bzr diff -c2
1984
 
 
1985
 
        To see the changes introduced by revision X::
 
1900
        To see the changes introduced in revision X::
1986
1901
        
1987
1902
            bzr diff -cX
1988
1903
 
1992
1907
 
1993
1908
            bzr diff -r<chosen_parent>..X
1994
1909
 
1995
 
        The changes between the current revision and the previous revision
1996
 
        (equivalent to -c-1 and -r-2..-1)
 
1910
        The changes introduced by revision 2 (equivalent to -r1..2)::
1997
1911
 
1998
 
            bzr diff -r-2..
 
1912
            bzr diff -c2
1999
1913
 
2000
1914
        Show just the differences for file NEWS::
2001
1915
 
2016
1930
        Same as 'bzr diff' but prefix paths with old/ and new/::
2017
1931
 
2018
1932
            bzr diff --prefix old/:new/
2019
 
            
2020
 
        Show the differences using a custom diff program with options::
2021
 
        
2022
 
            bzr diff --using /usr/bin/diff --diff-options -wu
2023
1933
    """
2024
1934
    _see_also = ['status']
2025
1935
    takes_args = ['file*']
2045
1955
            type=unicode,
2046
1956
            ),
2047
1957
        RegistryOption('format',
2048
 
            short_name='F',
2049
1958
            help='Diff format to use.',
2050
1959
            lazy_registry=('bzrlib.diff', 'format_registry'),
2051
 
            title='Diff format'),
 
1960
            value_switches=False, title='Diff format'),
2052
1961
        ]
2053
1962
    aliases = ['di', 'dif']
2054
1963
    encoding_type = 'exact'
2056
1965
    @display_command
2057
1966
    def run(self, revision=None, file_list=None, diff_options=None,
2058
1967
            prefix=None, old=None, new=None, using=None, format=None):
2059
 
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
 
1968
        from bzrlib.diff import (get_trees_and_branches_to_diff,
2060
1969
            show_diff_trees)
2061
1970
 
2062
1971
        if (prefix is None) or (prefix == '0'):
2083
1992
 
2084
1993
        (old_tree, new_tree,
2085
1994
         old_branch, new_branch,
2086
 
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
2087
 
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
2088
 
        # GNU diff on Windows uses ANSI encoding for filenames
2089
 
        path_encoding = osutils.get_diff_header_encoding()
 
1995
         specific_files, extra_trees) = get_trees_and_branches_to_diff(
 
1996
            file_list, revision, old, new, apply_view=True)
2090
1997
        return show_diff_trees(old_tree, new_tree, sys.stdout,
2091
1998
                               specific_files=specific_files,
2092
1999
                               external_diff_options=diff_options,
2093
2000
                               old_label=old_label, new_label=new_label,
2094
 
                               extra_trees=extra_trees,
2095
 
                               path_encoding=path_encoding,
2096
 
                               using=using,
 
2001
                               extra_trees=extra_trees, using=using,
2097
2002
                               format_cls=format)
2098
2003
 
2099
2004
 
2100
2005
class cmd_deleted(Command):
2101
 
    __doc__ = """List files deleted in the working tree.
 
2006
    """List files deleted in the working tree.
2102
2007
    """
2103
2008
    # TODO: Show files deleted since a previous revision, or
2104
2009
    # between two revisions.
2107
2012
    # level of effort but possibly much less IO.  (Or possibly not,
2108
2013
    # if the directories are very large...)
2109
2014
    _see_also = ['status', 'ls']
2110
 
    takes_options = ['directory', 'show-ids']
 
2015
    takes_options = ['show-ids']
2111
2016
 
2112
2017
    @display_command
2113
 
    def run(self, show_ids=False, directory=u'.'):
2114
 
        tree = WorkingTree.open_containing(directory)[0]
2115
 
        self.add_cleanup(tree.lock_read().unlock)
 
2018
    def run(self, show_ids=False):
 
2019
        tree = WorkingTree.open_containing(u'.')[0]
 
2020
        tree.lock_read()
 
2021
        self.add_cleanup(tree.unlock)
2116
2022
        old = tree.basis_tree()
2117
 
        self.add_cleanup(old.lock_read().unlock)
 
2023
        old.lock_read()
 
2024
        self.add_cleanup(old.unlock)
2118
2025
        for path, ie in old.inventory.iter_entries():
2119
2026
            if not tree.has_id(ie.file_id):
2120
2027
                self.outf.write(path)
2125
2032
 
2126
2033
 
2127
2034
class cmd_modified(Command):
2128
 
    __doc__ = """List files modified in working tree.
 
2035
    """List files modified in working tree.
2129
2036
    """
2130
2037
 
2131
2038
    hidden = True
2132
2039
    _see_also = ['status', 'ls']
2133
 
    takes_options = ['directory', 'null']
 
2040
    takes_options = [
 
2041
            Option('null',
 
2042
                   help='Write an ascii NUL (\\0) separator '
 
2043
                   'between files rather than a newline.')
 
2044
            ]
2134
2045
 
2135
2046
    @display_command
2136
 
    def run(self, null=False, directory=u'.'):
2137
 
        tree = WorkingTree.open_containing(directory)[0]
2138
 
        self.add_cleanup(tree.lock_read().unlock)
 
2047
    def run(self, null=False):
 
2048
        tree = WorkingTree.open_containing(u'.')[0]
2139
2049
        td = tree.changes_from(tree.basis_tree())
2140
 
        self.cleanup_now()
2141
2050
        for path, id, kind, text_modified, meta_modified in td.modified:
2142
2051
            if null:
2143
2052
                self.outf.write(path + '\0')
2146
2055
 
2147
2056
 
2148
2057
class cmd_added(Command):
2149
 
    __doc__ = """List files added in working tree.
 
2058
    """List files added in working tree.
2150
2059
    """
2151
2060
 
2152
2061
    hidden = True
2153
2062
    _see_also = ['status', 'ls']
2154
 
    takes_options = ['directory', 'null']
 
2063
    takes_options = [
 
2064
            Option('null',
 
2065
                   help='Write an ascii NUL (\\0) separator '
 
2066
                   'between files rather than a newline.')
 
2067
            ]
2155
2068
 
2156
2069
    @display_command
2157
 
    def run(self, null=False, directory=u'.'):
2158
 
        wt = WorkingTree.open_containing(directory)[0]
2159
 
        self.add_cleanup(wt.lock_read().unlock)
 
2070
    def run(self, null=False):
 
2071
        wt = WorkingTree.open_containing(u'.')[0]
 
2072
        wt.lock_read()
 
2073
        self.add_cleanup(wt.unlock)
2160
2074
        basis = wt.basis_tree()
2161
 
        self.add_cleanup(basis.lock_read().unlock)
 
2075
        basis.lock_read()
 
2076
        self.add_cleanup(basis.unlock)
2162
2077
        basis_inv = basis.inventory
2163
2078
        inv = wt.inventory
2164
2079
        for file_id in inv:
2165
 
            if basis_inv.has_id(file_id):
 
2080
            if file_id in basis_inv:
2166
2081
                continue
2167
2082
            if inv.is_root(file_id) and len(basis_inv) == 0:
2168
2083
                continue
2169
2084
            path = inv.id2path(file_id)
2170
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
 
2085
            if not os.access(osutils.abspath(path), os.F_OK):
2171
2086
                continue
2172
2087
            if null:
2173
2088
                self.outf.write(path + '\0')
2176
2091
 
2177
2092
 
2178
2093
class cmd_root(Command):
2179
 
    __doc__ = """Show the tree root directory.
 
2094
    """Show the tree root directory.
2180
2095
 
2181
2096
    The root is the nearest enclosing directory with a .bzr control
2182
2097
    directory."""
2206
2121
 
2207
2122
 
2208
2123
class cmd_log(Command):
2209
 
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2124
    """Show historical log for a branch or subset of a branch.
2210
2125
 
2211
2126
    log is bzr's default tool for exploring the history of a branch.
2212
2127
    The branch to use is taken from the first parameter. If no parameters
2373
2288
                   help='Show just the specified revision.'
2374
2289
                   ' See also "help revisionspec".'),
2375
2290
            'log-format',
2376
 
            RegistryOption('authors',
2377
 
                'What names to list as authors - first, all or committer.',
2378
 
                title='Authors',
2379
 
                lazy_registry=('bzrlib.log', 'author_list_registry'),
2380
 
            ),
2381
2291
            Option('levels',
2382
2292
                   short_name='n',
2383
2293
                   help='Number of levels to display - 0 for all, 1 for flat.',
2398
2308
                   help='Show changes made in each revision as a patch.'),
2399
2309
            Option('include-merges',
2400
2310
                   help='Show merged revisions like --levels 0 does.'),
2401
 
            Option('exclude-common-ancestry',
2402
 
                   help='Display only the revisions that are not part'
2403
 
                   ' of both ancestries (require -rX..Y)'
2404
 
                   ),
2405
 
            Option('signatures',
2406
 
                   help='Show digital signature validity'),
2407
2311
            ]
2408
2312
    encoding_type = 'replace'
2409
2313
 
2419
2323
            message=None,
2420
2324
            limit=None,
2421
2325
            show_diff=False,
2422
 
            include_merges=False,
2423
 
            authors=None,
2424
 
            exclude_common_ancestry=False,
2425
 
            signatures=False,
2426
 
            ):
 
2326
            include_merges=False):
2427
2327
        from bzrlib.log import (
2428
2328
            Logger,
2429
2329
            make_log_request_dict,
2430
2330
            _get_info_for_log_files,
2431
2331
            )
2432
2332
        direction = (forward and 'forward') or 'reverse'
2433
 
        if (exclude_common_ancestry
2434
 
            and (revision is None or len(revision) != 2)):
2435
 
            raise errors.BzrCommandError(
2436
 
                '--exclude-common-ancestry requires -r with two revisions')
2437
2333
        if include_merges:
2438
2334
            if levels is None:
2439
2335
                levels = 0
2455
2351
        if file_list:
2456
2352
            # find the file ids to log and check for directory filtering
2457
2353
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2458
 
                revision, file_list, self.add_cleanup)
 
2354
                revision, file_list)
 
2355
            self.add_cleanup(b.unlock)
2459
2356
            for relpath, file_id, kind in file_info_list:
2460
2357
                if file_id is None:
2461
2358
                    raise errors.BzrCommandError(
2479
2376
                location = '.'
2480
2377
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2481
2378
            b = dir.open_branch()
2482
 
            self.add_cleanup(b.lock_read().unlock)
 
2379
            b.lock_read()
 
2380
            self.add_cleanup(b.unlock)
2483
2381
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2484
2382
 
2485
 
        if b.get_config().validate_signatures_in_log():
2486
 
            signatures = True
2487
 
 
2488
 
        if signatures:
2489
 
            if not gpg.GPGStrategy.verify_signatures_available():
2490
 
                raise errors.GpgmeNotInstalled(None)
2491
 
 
2492
2383
        # Decide on the type of delta & diff filtering to use
2493
2384
        # TODO: add an --all-files option to make this configurable & consistent
2494
2385
        if not verbose:
2512
2403
                        show_timezone=timezone,
2513
2404
                        delta_format=get_verbosity_level(),
2514
2405
                        levels=levels,
2515
 
                        show_advice=levels is None,
2516
 
                        author_list_handler=authors)
 
2406
                        show_advice=levels is None)
2517
2407
 
2518
2408
        # Choose the algorithm for doing the logging. It's annoying
2519
2409
        # having multiple code paths like this but necessary until
2538
2428
            direction=direction, specific_fileids=file_ids,
2539
2429
            start_revision=rev1, end_revision=rev2, limit=limit,
2540
2430
            message_search=message, delta_type=delta_type,
2541
 
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2542
 
            exclude_common_ancestry=exclude_common_ancestry,
2543
 
            signature=signatures
2544
 
            )
 
2431
            diff_type=diff_type, _match_using_deltas=match_using_deltas)
2545
2432
        Logger(b, rqst).show(lf)
2546
2433
 
2547
2434
 
2605
2492
 
2606
2493
 
2607
2494
class cmd_touching_revisions(Command):
2608
 
    __doc__ = """Return revision-ids which affected a particular file.
 
2495
    """Return revision-ids which affected a particular file.
2609
2496
 
2610
2497
    A more user-friendly interface is "bzr log FILE".
2611
2498
    """
2618
2505
        tree, relpath = WorkingTree.open_containing(filename)
2619
2506
        file_id = tree.path2id(relpath)
2620
2507
        b = tree.branch
2621
 
        self.add_cleanup(b.lock_read().unlock)
 
2508
        b.lock_read()
 
2509
        self.add_cleanup(b.unlock)
2622
2510
        touching_revs = log.find_touching_revisions(b, file_id)
2623
2511
        for revno, revision_id, what in touching_revs:
2624
2512
            self.outf.write("%6d %s\n" % (revno, what))
2625
2513
 
2626
2514
 
2627
2515
class cmd_ls(Command):
2628
 
    __doc__ = """List files in a tree.
 
2516
    """List files in a tree.
2629
2517
    """
2630
2518
 
2631
2519
    _see_also = ['status', 'cat']
2637
2525
                   help='Recurse into subdirectories.'),
2638
2526
            Option('from-root',
2639
2527
                   help='Print paths relative to the root of the branch.'),
2640
 
            Option('unknown', short_name='u',
2641
 
                help='Print unknown files.'),
 
2528
            Option('unknown', help='Print unknown files.'),
2642
2529
            Option('versioned', help='Print versioned files.',
2643
2530
                   short_name='V'),
2644
 
            Option('ignored', short_name='i',
2645
 
                help='Print ignored files.'),
2646
 
            Option('kind', short_name='k',
 
2531
            Option('ignored', help='Print ignored files.'),
 
2532
            Option('null',
 
2533
                   help='Write an ascii NUL (\\0) separator '
 
2534
                   'between files rather than a newline.'),
 
2535
            Option('kind',
2647
2536
                   help='List entries of a particular kind: file, directory, symlink.',
2648
2537
                   type=unicode),
2649
 
            'null',
2650
2538
            'show-ids',
2651
 
            'directory',
2652
2539
            ]
2653
2540
    @display_command
2654
2541
    def run(self, revision=None, verbose=False,
2655
2542
            recursive=False, from_root=False,
2656
2543
            unknown=False, versioned=False, ignored=False,
2657
 
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2544
            null=False, kind=None, show_ids=False, path=None):
2658
2545
 
2659
2546
        if kind and kind not in ('file', 'directory', 'symlink'):
2660
2547
            raise errors.BzrCommandError('invalid kind specified')
2672
2559
                raise errors.BzrCommandError('cannot specify both --from-root'
2673
2560
                                             ' and PATH')
2674
2561
            fs_path = path
2675
 
        tree, branch, relpath = \
2676
 
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2562
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2563
            fs_path)
2677
2564
 
2678
2565
        # Calculate the prefix to use
2679
2566
        prefix = None
2694
2581
                view_str = views.view_display_str(view_files)
2695
2582
                note("Ignoring files outside view. View is %s" % view_str)
2696
2583
 
2697
 
        self.add_cleanup(tree.lock_read().unlock)
 
2584
        tree.lock_read()
 
2585
        self.add_cleanup(tree.unlock)
2698
2586
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2699
2587
            from_dir=relpath, recursive=recursive):
2700
2588
            # Apply additional masking
2742
2630
 
2743
2631
 
2744
2632
class cmd_unknowns(Command):
2745
 
    __doc__ = """List unknown files.
 
2633
    """List unknown files.
2746
2634
    """
2747
2635
 
2748
2636
    hidden = True
2749
2637
    _see_also = ['ls']
2750
 
    takes_options = ['directory']
2751
2638
 
2752
2639
    @display_command
2753
 
    def run(self, directory=u'.'):
2754
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
2640
    def run(self):
 
2641
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
2755
2642
            self.outf.write(osutils.quotefn(f) + '\n')
2756
2643
 
2757
2644
 
2758
2645
class cmd_ignore(Command):
2759
 
    __doc__ = """Ignore specified files or patterns.
 
2646
    """Ignore specified files or patterns.
2760
2647
 
2761
2648
    See ``bzr help patterns`` for details on the syntax of patterns.
2762
2649
 
2771
2658
    using this command or directly by using an editor, be sure to commit
2772
2659
    it.
2773
2660
    
2774
 
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2775
 
    the global ignore file can be found in the application data directory as
2776
 
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2777
 
    Global ignores are not touched by this command. The global ignore file
2778
 
    can be edited directly using an editor.
2779
 
 
2780
2661
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2781
2662
    precedence over regular ignores.  Such exceptions are used to specify
2782
2663
    files that should be versioned which would otherwise be ignored.
2784
2665
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2785
2666
    precedence over the '!' exception patterns.
2786
2667
 
2787
 
    :Notes: 
2788
 
        
2789
 
    * Ignore patterns containing shell wildcards must be quoted from
2790
 
      the shell on Unix.
2791
 
 
2792
 
    * Ignore patterns starting with "#" act as comments in the ignore file.
2793
 
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
2668
    Note: ignore patterns containing shell wildcards must be quoted from
 
2669
    the shell on Unix.
2794
2670
 
2795
2671
    :Examples:
2796
2672
        Ignore the top level Makefile::
2805
2681
 
2806
2682
            bzr ignore "!special.class"
2807
2683
 
2808
 
        Ignore files whose name begins with the "#" character::
2809
 
 
2810
 
            bzr ignore "RE:^#"
2811
 
 
2812
2684
        Ignore .o files under the lib directory::
2813
2685
 
2814
2686
            bzr ignore "lib/**/*.o"
2822
2694
            bzr ignore "RE:(?!debian/).*"
2823
2695
        
2824
2696
        Ignore everything except the "local" toplevel directory,
2825
 
        but always ignore autosave files ending in ~, even under local/::
 
2697
        but always ignore "*~" autosave files, even under local/::
2826
2698
        
2827
2699
            bzr ignore "*"
2828
2700
            bzr ignore "!./local"
2831
2703
 
2832
2704
    _see_also = ['status', 'ignored', 'patterns']
2833
2705
    takes_args = ['name_pattern*']
2834
 
    takes_options = ['directory',
2835
 
        Option('default-rules',
2836
 
               help='Display the default ignore rules that bzr uses.')
 
2706
    takes_options = [
 
2707
        Option('old-default-rules',
 
2708
               help='Write out the ignore rules bzr < 0.9 always used.')
2837
2709
        ]
2838
2710
 
2839
 
    def run(self, name_pattern_list=None, default_rules=None,
2840
 
            directory=u'.'):
 
2711
    def run(self, name_pattern_list=None, old_default_rules=None):
2841
2712
        from bzrlib import ignores
2842
 
        if default_rules is not None:
2843
 
            # dump the default rules and exit
2844
 
            for pattern in ignores.USER_DEFAULTS:
 
2713
        if old_default_rules is not None:
 
2714
            # dump the rules and exit
 
2715
            for pattern in ignores.OLD_DEFAULTS:
2845
2716
                self.outf.write("%s\n" % pattern)
2846
2717
            return
2847
2718
        if not name_pattern_list:
2848
2719
            raise errors.BzrCommandError("ignore requires at least one "
2849
 
                "NAME_PATTERN or --default-rules.")
 
2720
                                  "NAME_PATTERN or --old-default-rules")
2850
2721
        name_pattern_list = [globbing.normalize_pattern(p)
2851
2722
                             for p in name_pattern_list]
2852
 
        bad_patterns = ''
2853
 
        for p in name_pattern_list:
2854
 
            if not globbing.Globster.is_pattern_valid(p):
2855
 
                bad_patterns += ('\n  %s' % p)
2856
 
        if bad_patterns:
2857
 
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2858
 
            ui.ui_factory.show_error(msg)
2859
 
            raise errors.InvalidPattern('')
2860
2723
        for name_pattern in name_pattern_list:
2861
2724
            if (name_pattern[0] == '/' or
2862
2725
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2863
2726
                raise errors.BzrCommandError(
2864
2727
                    "NAME_PATTERN should not be an absolute path")
2865
 
        tree, relpath = WorkingTree.open_containing(directory)
 
2728
        tree, relpath = WorkingTree.open_containing(u'.')
2866
2729
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2867
2730
        ignored = globbing.Globster(name_pattern_list)
2868
2731
        matches = []
2869
 
        self.add_cleanup(tree.lock_read().unlock)
 
2732
        tree.lock_read()
2870
2733
        for entry in tree.list_files():
2871
2734
            id = entry[3]
2872
2735
            if id is not None:
2873
2736
                filename = entry[0]
2874
2737
                if ignored.match(filename):
2875
2738
                    matches.append(filename)
 
2739
        tree.unlock()
2876
2740
        if len(matches) > 0:
2877
2741
            self.outf.write("Warning: the following files are version controlled and"
2878
2742
                  " match your ignore pattern:\n%s"
2881
2745
 
2882
2746
 
2883
2747
class cmd_ignored(Command):
2884
 
    __doc__ = """List ignored files and the patterns that matched them.
 
2748
    """List ignored files and the patterns that matched them.
2885
2749
 
2886
2750
    List all the ignored files and the ignore pattern that caused the file to
2887
2751
    be ignored.
2893
2757
 
2894
2758
    encoding_type = 'replace'
2895
2759
    _see_also = ['ignore', 'ls']
2896
 
    takes_options = ['directory']
2897
2760
 
2898
2761
    @display_command
2899
 
    def run(self, directory=u'.'):
2900
 
        tree = WorkingTree.open_containing(directory)[0]
2901
 
        self.add_cleanup(tree.lock_read().unlock)
 
2762
    def run(self):
 
2763
        tree = WorkingTree.open_containing(u'.')[0]
 
2764
        tree.lock_read()
 
2765
        self.add_cleanup(tree.unlock)
2902
2766
        for path, file_class, kind, file_id, entry in tree.list_files():
2903
2767
            if file_class != 'I':
2904
2768
                continue
2908
2772
 
2909
2773
 
2910
2774
class cmd_lookup_revision(Command):
2911
 
    __doc__ = """Lookup the revision-id from a revision-number
 
2775
    """Lookup the revision-id from a revision-number
2912
2776
 
2913
2777
    :Examples:
2914
2778
        bzr lookup-revision 33
2915
2779
    """
2916
2780
    hidden = True
2917
2781
    takes_args = ['revno']
2918
 
    takes_options = ['directory']
2919
2782
 
2920
2783
    @display_command
2921
 
    def run(self, revno, directory=u'.'):
 
2784
    def run(self, revno):
2922
2785
        try:
2923
2786
            revno = int(revno)
2924
2787
        except ValueError:
2925
2788
            raise errors.BzrCommandError("not a valid revision-number: %r"
2926
2789
                                         % revno)
2927
 
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
 
2790
        revid = WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2928
2791
        self.outf.write("%s\n" % revid)
2929
2792
 
2930
2793
 
2931
2794
class cmd_export(Command):
2932
 
    __doc__ = """Export current or past revision to a destination directory or archive.
 
2795
    """Export current or past revision to a destination directory or archive.
2933
2796
 
2934
2797
    If no revision is specified this exports the last committed revision.
2935
2798
 
2956
2819
         zip                          .zip
2957
2820
      =================       =========================
2958
2821
    """
2959
 
    encoding = 'exact'
2960
2822
    takes_args = ['dest', 'branch_or_subdir?']
2961
 
    takes_options = ['directory',
 
2823
    takes_options = [
2962
2824
        Option('format',
2963
2825
               help="Type of file to export to.",
2964
2826
               type=unicode),
2973
2835
                    'revision in which it was changed.'),
2974
2836
        ]
2975
2837
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2976
 
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
 
2838
        root=None, filters=False, per_file_timestamps=False):
2977
2839
        from bzrlib.export import export
2978
2840
 
2979
2841
        if branch_or_subdir is None:
2980
 
            tree = WorkingTree.open_containing(directory)[0]
 
2842
            tree = WorkingTree.open_containing(u'.')[0]
2981
2843
            b = tree.branch
2982
2844
            subdir = None
2983
2845
        else:
2993
2855
 
2994
2856
 
2995
2857
class cmd_cat(Command):
2996
 
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
2858
    """Write the contents of a file as of a given revision to standard output.
2997
2859
 
2998
2860
    If no revision is nominated, the last revision is used.
2999
2861
 
3002
2864
    """
3003
2865
 
3004
2866
    _see_also = ['ls']
3005
 
    takes_options = ['directory',
 
2867
    takes_options = [
3006
2868
        Option('name-from-revision', help='The path name in the old tree.'),
3007
2869
        Option('filters', help='Apply content filters to display the '
3008
2870
                'convenience form.'),
3013
2875
 
3014
2876
    @display_command
3015
2877
    def run(self, filename, revision=None, name_from_revision=False,
3016
 
            filters=False, directory=None):
 
2878
            filters=False):
3017
2879
        if revision is not None and len(revision) != 1:
3018
2880
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
3019
2881
                                         " one revision specifier")
3020
2882
        tree, branch, relpath = \
3021
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
3022
 
        self.add_cleanup(branch.lock_read().unlock)
 
2883
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2884
        branch.lock_read()
 
2885
        self.add_cleanup(branch.unlock)
3023
2886
        return self._run(tree, branch, relpath, filename, revision,
3024
2887
                         name_from_revision, filters)
3025
2888
 
3028
2891
        if tree is None:
3029
2892
            tree = b.basis_tree()
3030
2893
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3031
 
        self.add_cleanup(rev_tree.lock_read().unlock)
 
2894
        rev_tree.lock_read()
 
2895
        self.add_cleanup(rev_tree.unlock)
3032
2896
 
3033
2897
        old_file_id = rev_tree.path2id(relpath)
3034
2898
 
3077
2941
 
3078
2942
 
3079
2943
class cmd_local_time_offset(Command):
3080
 
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
2944
    """Show the offset in seconds from GMT to local time."""
3081
2945
    hidden = True
3082
2946
    @display_command
3083
2947
    def run(self):
3086
2950
 
3087
2951
 
3088
2952
class cmd_commit(Command):
3089
 
    __doc__ = """Commit changes into a new revision.
 
2953
    """Commit changes into a new revision.
3090
2954
 
3091
2955
    An explanatory message needs to be given for each commit. This is
3092
2956
    often done by using the --message option (getting the message from the
3140
3004
      to trigger updates to external systems like bug trackers. The --fixes
3141
3005
      option can be used to record the association between a revision and
3142
3006
      one or more bugs. See ``bzr help bugs`` for details.
 
3007
 
 
3008
      A selective commit may fail in some cases where the committed
 
3009
      tree would be invalid. Consider::
 
3010
  
 
3011
        bzr init foo
 
3012
        mkdir foo/bar
 
3013
        bzr add foo/bar
 
3014
        bzr commit foo -m "committing foo"
 
3015
        bzr mv foo/bar foo/baz
 
3016
        mkdir foo/bar
 
3017
        bzr add foo/bar
 
3018
        bzr commit foo/bar -m "committing bar but not baz"
 
3019
  
 
3020
      In the example above, the last commit will fail by design. This gives
 
3021
      the user the opportunity to decide whether they want to commit the
 
3022
      rename at the same time, separately first, or not at all. (As a general
 
3023
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
3143
3024
    """
 
3025
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
3026
 
 
3027
    # TODO: Strict commit that fails if there are deleted files.
 
3028
    #       (what does "deleted files" mean ??)
 
3029
 
 
3030
    # TODO: Give better message for -s, --summary, used by tla people
 
3031
 
 
3032
    # XXX: verbose currently does nothing
3144
3033
 
3145
3034
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
3146
3035
    takes_args = ['selected*']
3175
3064
                         "the master branch until a normal commit "
3176
3065
                         "is performed."
3177
3066
                    ),
3178
 
             Option('show-diff', short_name='p',
 
3067
             Option('show-diff',
3179
3068
                    help='When no message is supplied, show the diff along'
3180
3069
                    ' with the status summary in the message editor.'),
3181
 
             Option('lossy', 
3182
 
                    help='When committing to a foreign version control '
3183
 
                    'system do not push data that can not be natively '
3184
 
                    'represented.'),
3185
3070
             ]
3186
3071
    aliases = ['ci', 'checkin']
3187
3072
 
3206
3091
 
3207
3092
    def run(self, message=None, file=None, verbose=False, selected_list=None,
3208
3093
            unchanged=False, strict=False, local=False, fixes=None,
3209
 
            author=None, show_diff=False, exclude=None, commit_time=None,
3210
 
            lossy=False):
 
3094
            author=None, show_diff=False, exclude=None, commit_time=None):
3211
3095
        from bzrlib.errors import (
3212
3096
            PointlessCommit,
3213
3097
            ConflictsInTree,
3216
3100
        from bzrlib.msgeditor import (
3217
3101
            edit_commit_message_encoded,
3218
3102
            generate_commit_message_template,
3219
 
            make_commit_message_template_encoded,
3220
 
            set_commit_message,
 
3103
            make_commit_message_template_encoded
3221
3104
        )
3222
3105
 
3223
3106
        commit_stamp = offset = None
3228
3111
                raise errors.BzrCommandError(
3229
3112
                    "Could not parse --commit-time: " + str(e))
3230
3113
 
 
3114
        # TODO: Need a blackbox test for invoking the external editor; may be
 
3115
        # slightly problematic to run this cross-platform.
 
3116
 
 
3117
        # TODO: do more checks that the commit will succeed before
 
3118
        # spending the user's valuable time typing a commit message.
 
3119
 
3231
3120
        properties = {}
3232
3121
 
3233
 
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
 
3122
        tree, selected_list = tree_files(selected_list)
3234
3123
        if selected_list == ['']:
3235
3124
            # workaround - commit of root of tree should be exactly the same
3236
3125
            # as just default commit in that tree, and succeed even though
3271
3160
        def get_message(commit_obj):
3272
3161
            """Callback to get commit message"""
3273
3162
            if file:
3274
 
                f = open(file)
3275
 
                try:
3276
 
                    my_message = f.read().decode(osutils.get_user_encoding())
3277
 
                finally:
3278
 
                    f.close()
 
3163
                my_message = codecs.open(
 
3164
                    file, 'rt', osutils.get_user_encoding()).read()
3279
3165
            elif message is not None:
3280
3166
                my_message = message
3281
3167
            else:
3289
3175
                # make_commit_message_template_encoded returns user encoding.
3290
3176
                # We probably want to be using edit_commit_message instead to
3291
3177
                # avoid this.
3292
 
                my_message = set_commit_message(commit_obj)
3293
 
                if my_message is None:
3294
 
                    start_message = generate_commit_message_template(commit_obj)
3295
 
                    my_message = edit_commit_message_encoded(text,
3296
 
                        start_message=start_message)
 
3178
                start_message = generate_commit_message_template(commit_obj)
 
3179
                my_message = edit_commit_message_encoded(text,
 
3180
                    start_message=start_message)
3297
3181
                if my_message is None:
3298
3182
                    raise errors.BzrCommandError("please specify a commit"
3299
3183
                        " message with either --message or --file")
3312
3196
                        reporter=None, verbose=verbose, revprops=properties,
3313
3197
                        authors=author, timestamp=commit_stamp,
3314
3198
                        timezone=offset,
3315
 
                        exclude=tree.safe_relpath_files(exclude),
3316
 
                        lossy=lossy)
 
3199
                        exclude=safe_relpath_files(tree, exclude))
3317
3200
        except PointlessCommit:
3318
3201
            raise errors.BzrCommandError("No changes to commit."
3319
 
                " Please 'bzr add' the files you want to commit, or use"
3320
 
                " --unchanged to force an empty commit.")
 
3202
                              " Use --unchanged to commit anyhow.")
3321
3203
        except ConflictsInTree:
3322
3204
            raise errors.BzrCommandError('Conflicts detected in working '
3323
3205
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3334
3216
 
3335
3217
 
3336
3218
class cmd_check(Command):
3337
 
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3219
    """Validate working tree structure, branch consistency and repository history.
3338
3220
 
3339
3221
    This command checks various invariants about branch and repository storage
3340
3222
    to detect data corruption or bzr bugs.
3404
3286
 
3405
3287
 
3406
3288
class cmd_upgrade(Command):
3407
 
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
3408
 
 
3409
 
    When the default format has changed after a major new release of
3410
 
    Bazaar, you may be informed during certain operations that you
3411
 
    should upgrade. Upgrading to a newer format may improve performance
3412
 
    or make new features available. It may however limit interoperability
3413
 
    with older repositories or with older versions of Bazaar.
3414
 
 
3415
 
    If you wish to upgrade to a particular format rather than the
3416
 
    current default, that can be specified using the --format option.
3417
 
    As a consequence, you can use the upgrade command this way to
3418
 
    "downgrade" to an earlier format, though some conversions are
3419
 
    a one way process (e.g. changing from the 1.x default to the
3420
 
    2.x default) so downgrading is not always possible.
3421
 
 
3422
 
    A backup.bzr.~#~ directory is created at the start of the conversion
3423
 
    process (where # is a number). By default, this is left there on
3424
 
    completion. If the conversion fails, delete the new .bzr directory
3425
 
    and rename this one back in its place. Use the --clean option to ask
3426
 
    for the backup.bzr directory to be removed on successful conversion.
3427
 
    Alternatively, you can delete it by hand if everything looks good
3428
 
    afterwards.
3429
 
 
3430
 
    If the location given is a shared repository, dependent branches
3431
 
    are also converted provided the repository converts successfully.
3432
 
    If the conversion of a branch fails, remaining branches are still
3433
 
    tried.
3434
 
 
3435
 
    For more information on upgrades, see the Bazaar Upgrade Guide,
3436
 
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
 
3289
    """Upgrade branch storage to current format.
 
3290
 
 
3291
    The check command or bzr developers may sometimes advise you to run
 
3292
    this command. When the default format has changed you may also be warned
 
3293
    during other operations to upgrade.
3437
3294
    """
3438
3295
 
3439
 
    _see_also = ['check', 'reconcile', 'formats']
 
3296
    _see_also = ['check']
3440
3297
    takes_args = ['url?']
3441
3298
    takes_options = [
3442
 
        RegistryOption('format',
3443
 
            help='Upgrade to a specific format.  See "bzr help'
3444
 
                 ' formats" for details.',
3445
 
            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3446
 
            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3447
 
            value_switches=True, title='Branch format'),
3448
 
        Option('clean',
3449
 
            help='Remove the backup.bzr directory if successful.'),
3450
 
        Option('dry-run',
3451
 
            help="Show what would be done, but don't actually do anything."),
3452
 
    ]
 
3299
                    RegistryOption('format',
 
3300
                        help='Upgrade to a specific format.  See "bzr help'
 
3301
                             ' formats" for details.',
 
3302
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3303
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
 
3304
                        value_switches=True, title='Branch format'),
 
3305
                    ]
3453
3306
 
3454
 
    def run(self, url='.', format=None, clean=False, dry_run=False):
 
3307
    def run(self, url='.', format=None):
3455
3308
        from bzrlib.upgrade import upgrade
3456
 
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3457
 
        if exceptions:
3458
 
            if len(exceptions) == 1:
3459
 
                # Compatibility with historical behavior
3460
 
                raise exceptions[0]
3461
 
            else:
3462
 
                return 3
 
3309
        upgrade(url, format)
3463
3310
 
3464
3311
 
3465
3312
class cmd_whoami(Command):
3466
 
    __doc__ = """Show or set bzr user id.
 
3313
    """Show or set bzr user id.
3467
3314
 
3468
3315
    :Examples:
3469
3316
        Show the email of the current user::
3474
3321
 
3475
3322
            bzr whoami "Frank Chu <fchu@example.com>"
3476
3323
    """
3477
 
    takes_options = [ 'directory',
3478
 
                      Option('email',
 
3324
    takes_options = [ Option('email',
3479
3325
                             help='Display email address only.'),
3480
3326
                      Option('branch',
3481
3327
                             help='Set identity for the current branch instead of '
3485
3331
    encoding_type = 'replace'
3486
3332
 
3487
3333
    @display_command
3488
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
3334
    def run(self, email=False, branch=False, name=None):
3489
3335
        if name is None:
3490
 
            if directory is None:
3491
 
                # use branch if we're inside one; otherwise global config
3492
 
                try:
3493
 
                    c = Branch.open_containing(u'.')[0].get_config()
3494
 
                except errors.NotBranchError:
3495
 
                    c = _mod_config.GlobalConfig()
3496
 
            else:
3497
 
                c = Branch.open(directory).get_config()
 
3336
            # use branch if we're inside one; otherwise global config
 
3337
            try:
 
3338
                c = Branch.open_containing('.')[0].get_config()
 
3339
            except errors.NotBranchError:
 
3340
                c = config.GlobalConfig()
3498
3341
            if email:
3499
3342
                self.outf.write(c.user_email() + '\n')
3500
3343
            else:
3501
3344
                self.outf.write(c.username() + '\n')
3502
3345
            return
3503
3346
 
3504
 
        if email:
3505
 
            raise errors.BzrCommandError("--email can only be used to display existing "
3506
 
                                         "identity")
3507
 
 
3508
3347
        # display a warning if an email address isn't included in the given name.
3509
3348
        try:
3510
 
            _mod_config.extract_email_address(name)
 
3349
            config.extract_email_address(name)
3511
3350
        except errors.NoEmailInUsername, e:
3512
3351
            warning('"%s" does not seem to contain an email address.  '
3513
3352
                    'This is allowed, but not recommended.', name)
3514
3353
 
3515
3354
        # use global config unless --branch given
3516
3355
        if branch:
3517
 
            if directory is None:
3518
 
                c = Branch.open_containing(u'.')[0].get_config()
3519
 
            else:
3520
 
                c = Branch.open(directory).get_config()
 
3356
            c = Branch.open_containing('.')[0].get_config()
3521
3357
        else:
3522
 
            c = _mod_config.GlobalConfig()
 
3358
            c = config.GlobalConfig()
3523
3359
        c.set_user_option('email', name)
3524
3360
 
3525
3361
 
3526
3362
class cmd_nick(Command):
3527
 
    __doc__ = """Print or set the branch nickname.
 
3363
    """Print or set the branch nickname.
3528
3364
 
3529
3365
    If unset, the tree root directory name is used as the nickname.
3530
3366
    To print the current nickname, execute with no argument.
3535
3371
 
3536
3372
    _see_also = ['info']
3537
3373
    takes_args = ['nickname?']
3538
 
    takes_options = ['directory']
3539
 
    def run(self, nickname=None, directory=u'.'):
3540
 
        branch = Branch.open_containing(directory)[0]
 
3374
    def run(self, nickname=None):
 
3375
        branch = Branch.open_containing(u'.')[0]
3541
3376
        if nickname is None:
3542
3377
            self.printme(branch)
3543
3378
        else:
3549
3384
 
3550
3385
 
3551
3386
class cmd_alias(Command):
3552
 
    __doc__ = """Set/unset and display aliases.
 
3387
    """Set/unset and display aliases.
3553
3388
 
3554
3389
    :Examples:
3555
3390
        Show the current aliases::
3592
3427
                'bzr alias --remove expects an alias to remove.')
3593
3428
        # If alias is not found, print something like:
3594
3429
        # unalias: foo: not found
3595
 
        c = _mod_config.GlobalConfig()
 
3430
        c = config.GlobalConfig()
3596
3431
        c.unset_alias(alias_name)
3597
3432
 
3598
3433
    @display_command
3599
3434
    def print_aliases(self):
3600
3435
        """Print out the defined aliases in a similar format to bash."""
3601
 
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3436
        aliases = config.GlobalConfig().get_aliases()
3602
3437
        for key, value in sorted(aliases.iteritems()):
3603
3438
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3604
3439
 
3614
3449
 
3615
3450
    def set_alias(self, alias_name, alias_command):
3616
3451
        """Save the alias in the global config."""
3617
 
        c = _mod_config.GlobalConfig()
 
3452
        c = config.GlobalConfig()
3618
3453
        c.set_alias(alias_name, alias_command)
3619
3454
 
3620
3455
 
3621
3456
class cmd_selftest(Command):
3622
 
    __doc__ = """Run internal test suite.
 
3457
    """Run internal test suite.
3623
3458
 
3624
3459
    If arguments are given, they are regular expressions that say which tests
3625
3460
    should run.  Tests matching any expression are run, and other tests are
3655
3490
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3656
3491
    into a pdb postmortem session.
3657
3492
 
3658
 
    The --coverage=DIRNAME global option produces a report with covered code
3659
 
    indicated.
3660
 
 
3661
3493
    :Examples:
3662
3494
        Run only tests relating to 'ignore'::
3663
3495
 
3674
3506
        if typestring == "sftp":
3675
3507
            from bzrlib.tests import stub_sftp
3676
3508
            return stub_sftp.SFTPAbsoluteServer
3677
 
        elif typestring == "memory":
 
3509
        if typestring == "memory":
3678
3510
            from bzrlib.tests import test_server
3679
3511
            return memory.MemoryServer
3680
 
        elif typestring == "fakenfs":
 
3512
        if typestring == "fakenfs":
3681
3513
            from bzrlib.tests import test_server
3682
3514
            return test_server.FakeNFSServer
3683
3515
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3696
3528
                                 'throughout the test suite.',
3697
3529
                            type=get_transport_type),
3698
3530
                     Option('benchmark',
3699
 
                            help='Run the benchmarks rather than selftests.',
3700
 
                            hidden=True),
 
3531
                            help='Run the benchmarks rather than selftests.'),
3701
3532
                     Option('lsprof-timed',
3702
3533
                            help='Generate lsprof output for benchmarked'
3703
3534
                                 ' sections of code.'),
3704
3535
                     Option('lsprof-tests',
3705
3536
                            help='Generate lsprof output for each test.'),
 
3537
                     Option('cache-dir', type=str,
 
3538
                            help='Cache intermediate benchmark output in this '
 
3539
                                 'directory.'),
3706
3540
                     Option('first',
3707
3541
                            help='Run all tests, but run specified tests first.',
3708
3542
                            short_name='f',
3717
3551
                     Option('randomize', type=str, argname="SEED",
3718
3552
                            help='Randomize the order of tests using the given'
3719
3553
                                 ' seed or "now" for the current time.'),
3720
 
                     ListOption('exclude', type=str, argname="PATTERN",
3721
 
                                short_name='x',
3722
 
                                help='Exclude tests that match this regular'
3723
 
                                ' expression.'),
 
3554
                     Option('exclude', type=str, argname="PATTERN",
 
3555
                            short_name='x',
 
3556
                            help='Exclude tests that match this regular'
 
3557
                                 ' expression.'),
3724
3558
                     Option('subunit',
3725
3559
                        help='Output test progress via subunit.'),
3726
3560
                     Option('strict', help='Fail on missing dependencies or '
3733
3567
                                param_name='starting_with', short_name='s',
3734
3568
                                help=
3735
3569
                                'Load only the tests starting with TESTID.'),
3736
 
                     Option('sync',
3737
 
                            help="By default we disable fsync and fdatasync"
3738
 
                                 " while running the test suite.")
3739
3570
                     ]
3740
3571
    encoding_type = 'replace'
3741
3572
 
3745
3576
 
3746
3577
    def run(self, testspecs_list=None, verbose=False, one=False,
3747
3578
            transport=None, benchmark=None,
3748
 
            lsprof_timed=None,
 
3579
            lsprof_timed=None, cache_dir=None,
3749
3580
            first=False, list_only=False,
3750
3581
            randomize=None, exclude=None, strict=False,
3751
3582
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3752
 
            parallel=None, lsprof_tests=False,
3753
 
            sync=False):
3754
 
        from bzrlib import tests
3755
 
 
 
3583
            parallel=None, lsprof_tests=False):
 
3584
        from bzrlib.tests import selftest
 
3585
        import bzrlib.benchmarks as benchmarks
 
3586
        from bzrlib.benchmarks import tree_creator
 
3587
 
 
3588
        # Make deprecation warnings visible, unless -Werror is set
 
3589
        symbol_versioning.activate_deprecation_warnings(override=False)
 
3590
 
 
3591
        if cache_dir is not None:
 
3592
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3756
3593
        if testspecs_list is not None:
3757
3594
            pattern = '|'.join(testspecs_list)
3758
3595
        else:
3764
3601
                raise errors.BzrCommandError("subunit not available. subunit "
3765
3602
                    "needs to be installed to use --subunit.")
3766
3603
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3767
 
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3768
 
            # stdout, which would corrupt the subunit stream. 
3769
 
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3770
 
            # following code can be deleted when it's sufficiently deployed
3771
 
            # -- vila/mgz 20100514
3772
 
            if (sys.platform == "win32"
3773
 
                and getattr(sys.stdout, 'fileno', None) is not None):
3774
 
                import msvcrt
3775
 
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3776
3604
        if parallel:
3777
3605
            self.additional_selftest_args.setdefault(
3778
3606
                'suite_decorators', []).append(parallel)
3779
3607
        if benchmark:
3780
 
            raise errors.BzrCommandError(
3781
 
                "--benchmark is no longer supported from bzr 2.2; "
3782
 
                "use bzr-usertest instead")
3783
 
        test_suite_factory = None
3784
 
        if not exclude:
3785
 
            exclude_pattern = None
 
3608
            test_suite_factory = benchmarks.test_suite
 
3609
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3610
            verbose = not is_quiet()
 
3611
            # TODO: should possibly lock the history file...
 
3612
            benchfile = open(".perf_history", "at", buffering=1)
 
3613
            self.add_cleanup(benchfile.close)
3786
3614
        else:
3787
 
            exclude_pattern = '(' + '|'.join(exclude) + ')'
3788
 
        if not sync:
3789
 
            self._disable_fsync()
 
3615
            test_suite_factory = None
 
3616
            benchfile = None
3790
3617
        selftest_kwargs = {"verbose": verbose,
3791
3618
                          "pattern": pattern,
3792
3619
                          "stop_on_failure": one,
3794
3621
                          "test_suite_factory": test_suite_factory,
3795
3622
                          "lsprof_timed": lsprof_timed,
3796
3623
                          "lsprof_tests": lsprof_tests,
 
3624
                          "bench_history": benchfile,
3797
3625
                          "matching_tests_first": first,
3798
3626
                          "list_only": list_only,
3799
3627
                          "random_seed": randomize,
3800
 
                          "exclude_pattern": exclude_pattern,
 
3628
                          "exclude_pattern": exclude,
3801
3629
                          "strict": strict,
3802
3630
                          "load_list": load_list,
3803
3631
                          "debug_flags": debugflag,
3804
3632
                          "starting_with": starting_with
3805
3633
                          }
3806
3634
        selftest_kwargs.update(self.additional_selftest_args)
3807
 
 
3808
 
        # Make deprecation warnings visible, unless -Werror is set
3809
 
        cleanup = symbol_versioning.activate_deprecation_warnings(
3810
 
            override=False)
3811
 
        try:
3812
 
            result = tests.selftest(**selftest_kwargs)
3813
 
        finally:
3814
 
            cleanup()
 
3635
        result = selftest(**selftest_kwargs)
3815
3636
        return int(not result)
3816
3637
 
3817
 
    def _disable_fsync(self):
3818
 
        """Change the 'os' functionality to not synchronize."""
3819
 
        self._orig_fsync = getattr(os, 'fsync', None)
3820
 
        if self._orig_fsync is not None:
3821
 
            os.fsync = lambda filedes: None
3822
 
        self._orig_fdatasync = getattr(os, 'fdatasync', None)
3823
 
        if self._orig_fdatasync is not None:
3824
 
            os.fdatasync = lambda filedes: None
3825
 
 
3826
3638
 
3827
3639
class cmd_version(Command):
3828
 
    __doc__ = """Show version of bzr."""
 
3640
    """Show version of bzr."""
3829
3641
 
3830
3642
    encoding_type = 'replace'
3831
3643
    takes_options = [
3842
3654
 
3843
3655
 
3844
3656
class cmd_rocks(Command):
3845
 
    __doc__ = """Statement of optimism."""
 
3657
    """Statement of optimism."""
3846
3658
 
3847
3659
    hidden = True
3848
3660
 
3852
3664
 
3853
3665
 
3854
3666
class cmd_find_merge_base(Command):
3855
 
    __doc__ = """Find and print a base revision for merging two branches."""
 
3667
    """Find and print a base revision for merging two branches."""
3856
3668
    # TODO: Options to specify revisions on either side, as if
3857
3669
    #       merging only part of the history.
3858
3670
    takes_args = ['branch', 'other']
3864
3676
 
3865
3677
        branch1 = Branch.open_containing(branch)[0]
3866
3678
        branch2 = Branch.open_containing(other)[0]
3867
 
        self.add_cleanup(branch1.lock_read().unlock)
3868
 
        self.add_cleanup(branch2.lock_read().unlock)
 
3679
        branch1.lock_read()
 
3680
        self.add_cleanup(branch1.unlock)
 
3681
        branch2.lock_read()
 
3682
        self.add_cleanup(branch2.unlock)
3869
3683
        last1 = ensure_null(branch1.last_revision())
3870
3684
        last2 = ensure_null(branch2.last_revision())
3871
3685
 
3876
3690
 
3877
3691
 
3878
3692
class cmd_merge(Command):
3879
 
    __doc__ = """Perform a three-way merge.
 
3693
    """Perform a three-way merge.
3880
3694
 
3881
3695
    The source of the merge can be specified either in the form of a branch,
3882
3696
    or in the form of a path to a file containing a merge directive generated
3883
3697
    with bzr send. If neither is specified, the default is the upstream branch
3884
 
    or the branch most recently merged using --remember.  The source of the
3885
 
    merge may also be specified in the form of a path to a file in another
3886
 
    branch:  in this case, only the modifications to that file are merged into
3887
 
    the current working tree.
3888
 
 
3889
 
    When merging from a branch, by default bzr will try to merge in all new
3890
 
    work from the other branch, automatically determining an appropriate base
3891
 
    revision.  If this fails, you may need to give an explicit base.
3892
 
 
3893
 
    To pick a different ending revision, pass "--revision OTHER".  bzr will
3894
 
    try to merge in all new work up to and including revision OTHER.
3895
 
 
3896
 
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
3897
 
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
3898
 
    causes some revisions to be skipped, i.e. if the destination branch does
3899
 
    not already contain revision BASE, such a merge is commonly referred to as
3900
 
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
3901
 
    cherrypicks. The changes look like a normal commit, and the history of the
3902
 
    changes from the other branch is not stored in the commit.
3903
 
 
3904
 
    Revision numbers are always relative to the source branch.
 
3698
    or the branch most recently merged using --remember.
 
3699
 
 
3700
    When merging a branch, by default the tip will be merged. To pick a different
 
3701
    revision, pass --revision. If you specify two values, the first will be used as
 
3702
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
3703
    available revisions, like this is commonly referred to as "cherrypicking".
 
3704
 
 
3705
    Revision numbers are always relative to the branch being merged.
 
3706
 
 
3707
    By default, bzr will try to merge in all new work from the other
 
3708
    branch, automatically determining an appropriate base.  If this
 
3709
    fails, you may need to give an explicit base.
3905
3710
 
3906
3711
    Merge will do its best to combine the changes in two branches, but there
3907
3712
    are some kinds of problems only a human can fix.  When it encounters those,
3910
3715
 
3911
3716
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
3912
3717
 
3913
 
    If there is no default branch set, the first merge will set it (use
3914
 
    --no-remember to avoid settting it). After that, you can omit the branch
3915
 
    to use the default.  To change the default, use --remember. The value will
3916
 
    only be saved if the remote location can be accessed.
 
3718
    If there is no default branch set, the first merge will set it. After
 
3719
    that, you can omit the branch to use the default.  To change the
 
3720
    default, use --remember. The value will only be saved if the remote
 
3721
    location can be accessed.
3917
3722
 
3918
3723
    The results of the merge are placed into the destination working
3919
3724
    directory, where they can be reviewed (with bzr diff), tested, and then
3920
3725
    committed to record the result of the merge.
3921
3726
 
3922
3727
    merge refuses to run if there are any uncommitted changes, unless
3923
 
    --force is given.  If --force is given, then the changes from the source 
3924
 
    will be merged with the current working tree, including any uncommitted
3925
 
    changes in the tree.  The --force option can also be used to create a
 
3728
    --force is given. The --force option can also be used to create a
3926
3729
    merge revision which has more than two parents.
3927
3730
 
3928
3731
    If one would like to merge changes from the working tree of the other
3933
3736
    you to apply each diff hunk and file change, similar to "shelve".
3934
3737
 
3935
3738
    :Examples:
3936
 
        To merge all new revisions from bzr.dev::
 
3739
        To merge the latest revision from bzr.dev::
3937
3740
 
3938
3741
            bzr merge ../bzr.dev
3939
3742
 
3976
3779
                ' completely merged into the source, pull from the'
3977
3780
                ' source rather than merging.  When this happens,'
3978
3781
                ' you do not need to commit the result.'),
3979
 
        custom_help('directory',
 
3782
        Option('directory',
3980
3783
               help='Branch to merge into, '
3981
 
                    'rather than the one containing the working directory.'),
 
3784
                    'rather than the one containing the working directory.',
 
3785
               short_name='d',
 
3786
               type=unicode,
 
3787
               ),
3982
3788
        Option('preview', help='Instead of merging, show a diff of the'
3983
3789
               ' merge.'),
3984
3790
        Option('interactive', help='Select changes interactively.',
3986
3792
    ]
3987
3793
 
3988
3794
    def run(self, location=None, revision=None, force=False,
3989
 
            merge_type=None, show_base=False, reprocess=None, remember=None,
 
3795
            merge_type=None, show_base=False, reprocess=None, remember=False,
3990
3796
            uncommitted=False, pull=False,
3991
3797
            directory=None,
3992
3798
            preview=False,
4000
3806
        merger = None
4001
3807
        allow_pending = True
4002
3808
        verified = 'inapplicable'
4003
 
 
4004
3809
        tree = WorkingTree.open_containing(directory)[0]
4005
 
        if tree.branch.revno() == 0:
4006
 
            raise errors.BzrCommandError('Merging into empty branches not currently supported, '
4007
 
                                         'https://bugs.launchpad.net/bzr/+bug/308562')
4008
3810
 
4009
3811
        try:
4010
3812
            basis_tree = tree.revision_tree(tree.last_revision())
4021
3823
            unversioned_filter=tree.is_ignored, view_info=view_info)
4022
3824
        pb = ui.ui_factory.nested_progress_bar()
4023
3825
        self.add_cleanup(pb.finished)
4024
 
        self.add_cleanup(tree.lock_write().unlock)
 
3826
        tree.lock_write()
 
3827
        self.add_cleanup(tree.unlock)
4025
3828
        if location is not None:
4026
3829
            try:
4027
3830
                mergeable = bundle.read_mergeable_from_url(location,
4056
3859
        self.sanity_check_merger(merger)
4057
3860
        if (merger.base_rev_id == merger.other_rev_id and
4058
3861
            merger.other_rev_id is not None):
4059
 
            # check if location is a nonexistent file (and not a branch) to
4060
 
            # disambiguate the 'Nothing to do'
4061
 
            if merger.interesting_files:
4062
 
                if not merger.other_tree.has_filename(
4063
 
                    merger.interesting_files[0]):
4064
 
                    note("merger: " + str(merger))
4065
 
                    raise errors.PathsDoNotExist([location])
4066
3862
            note('Nothing to do.')
4067
3863
            return 0
4068
 
        if pull and not preview:
 
3864
        if pull:
4069
3865
            if merger.interesting_files is not None:
4070
3866
                raise errors.BzrCommandError('Cannot pull individual files')
4071
3867
            if (merger.base_rev_id == tree.last_revision()):
4095
3891
    def _do_preview(self, merger):
4096
3892
        from bzrlib.diff import show_diff_trees
4097
3893
        result_tree = self._get_preview(merger)
4098
 
        path_encoding = osutils.get_diff_header_encoding()
4099
3894
        show_diff_trees(merger.this_tree, result_tree, self.outf,
4100
 
                        old_label='', new_label='',
4101
 
                        path_encoding=path_encoding)
 
3895
                        old_label='', new_label='')
4102
3896
 
4103
3897
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
4104
3898
        merger.change_reporter = change_reporter
4180
3974
        if other_revision_id is None:
4181
3975
            other_revision_id = _mod_revision.ensure_null(
4182
3976
                other_branch.last_revision())
4183
 
        # Remember where we merge from. We need to remember if:
4184
 
        # - user specify a location (and we don't merge from the parent
4185
 
        #   branch)
4186
 
        # - user ask to remember or there is no previous location set to merge
4187
 
        #   from and user didn't ask to *not* remember
4188
 
        if (user_location is not None
4189
 
            and ((remember
4190
 
                  or (remember is None
4191
 
                      and tree.branch.get_submit_branch() is None)))):
 
3977
        # Remember where we merge from
 
3978
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3979
             user_location is not None):
4192
3980
            tree.branch.set_submit_branch(other_branch.base)
4193
 
        # Merge tags (but don't set them in the master branch yet, the user
4194
 
        # might revert this merge).  Commit will propagate them.
4195
 
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
 
3981
        _merge_tags_if_possible(other_branch, tree.branch)
4196
3982
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4197
3983
            other_revision_id, base_revision_id, other_branch, base_branch)
4198
3984
        if other_path != '':
4265
4051
 
4266
4052
 
4267
4053
class cmd_remerge(Command):
4268
 
    __doc__ = """Redo a merge.
 
4054
    """Redo a merge.
4269
4055
 
4270
4056
    Use this if you want to try a different merge technique while resolving
4271
4057
    conflicts.  Some merge techniques are better than others, and remerge
4299
4085
        from bzrlib.conflicts import restore
4300
4086
        if merge_type is None:
4301
4087
            merge_type = _mod_merge.Merge3Merger
4302
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4303
 
        self.add_cleanup(tree.lock_write().unlock)
 
4088
        tree, file_list = tree_files(file_list)
 
4089
        tree.lock_write()
 
4090
        self.add_cleanup(tree.unlock)
4304
4091
        parents = tree.get_parent_ids()
4305
4092
        if len(parents) != 2:
4306
4093
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4359
4146
 
4360
4147
 
4361
4148
class cmd_revert(Command):
4362
 
    __doc__ = """Revert files to a previous revision.
 
4149
    """Revert files to a previous revision.
4363
4150
 
4364
4151
    Giving a list of files will revert only those files.  Otherwise, all files
4365
4152
    will be reverted.  If the revision is not specified with '--revision', the
4366
4153
    last committed revision is used.
4367
4154
 
4368
4155
    To remove only some changes, without reverting to a prior version, use
4369
 
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
4370
 
    will remove the changes introduced by the second last commit (-2), without
4371
 
    affecting the changes introduced by the last commit (-1).  To remove
4372
 
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
4156
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
4157
    changes introduced by -2, without affecting the changes introduced by -1.
 
4158
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4373
4159
 
4374
4160
    By default, any files that have been manually changed will be backed up
4375
4161
    first.  (Files changed only by merge are not backed up.)  Backup files have
4405
4191
    target branches.
4406
4192
    """
4407
4193
 
4408
 
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4194
    _see_also = ['cat', 'export']
4409
4195
    takes_options = [
4410
4196
        'revision',
4411
4197
        Option('no-backup', "Do not save backups of reverted files."),
4416
4202
 
4417
4203
    def run(self, revision=None, no_backup=False, file_list=None,
4418
4204
            forget_merges=None):
4419
 
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4420
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
4205
        tree, file_list = tree_files(file_list)
 
4206
        tree.lock_write()
 
4207
        self.add_cleanup(tree.unlock)
4421
4208
        if forget_merges:
4422
4209
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4423
4210
        else:
4431
4218
 
4432
4219
 
4433
4220
class cmd_assert_fail(Command):
4434
 
    __doc__ = """Test reporting of assertion failures"""
 
4221
    """Test reporting of assertion failures"""
4435
4222
    # intended just for use in testing
4436
4223
 
4437
4224
    hidden = True
4441
4228
 
4442
4229
 
4443
4230
class cmd_help(Command):
4444
 
    __doc__ = """Show help on a command or other topic.
 
4231
    """Show help on a command or other topic.
4445
4232
    """
4446
4233
 
4447
4234
    _see_also = ['topics']
4460
4247
 
4461
4248
 
4462
4249
class cmd_shell_complete(Command):
4463
 
    __doc__ = """Show appropriate completions for context.
 
4250
    """Show appropriate completions for context.
4464
4251
 
4465
4252
    For a list of all available commands, say 'bzr shell-complete'.
4466
4253
    """
4475
4262
 
4476
4263
 
4477
4264
class cmd_missing(Command):
4478
 
    __doc__ = """Show unmerged/unpulled revisions between two branches.
 
4265
    """Show unmerged/unpulled revisions between two branches.
4479
4266
 
4480
4267
    OTHER_BRANCH may be local or remote.
4481
4268
 
4512
4299
    _see_also = ['merge', 'pull']
4513
4300
    takes_args = ['other_branch?']
4514
4301
    takes_options = [
4515
 
        'directory',
4516
4302
        Option('reverse', 'Reverse the order of revisions.'),
4517
4303
        Option('mine-only',
4518
4304
               'Display changes in the local branch only.'),
4540
4326
            theirs_only=False,
4541
4327
            log_format=None, long=False, short=False, line=False,
4542
4328
            show_ids=False, verbose=False, this=False, other=False,
4543
 
            include_merges=False, revision=None, my_revision=None,
4544
 
            directory=u'.'):
 
4329
            include_merges=False, revision=None, my_revision=None):
4545
4330
        from bzrlib.missing import find_unmerged, iter_log_revisions
4546
4331
        def message(s):
4547
4332
            if not is_quiet():
4560
4345
        elif theirs_only:
4561
4346
            restrict = 'remote'
4562
4347
 
4563
 
        local_branch = Branch.open_containing(directory)[0]
4564
 
        self.add_cleanup(local_branch.lock_read().unlock)
 
4348
        local_branch = Branch.open_containing(u".")[0]
 
4349
        local_branch.lock_read()
 
4350
        self.add_cleanup(local_branch.unlock)
4565
4351
 
4566
4352
        parent = local_branch.get_parent()
4567
4353
        if other_branch is None:
4578
4364
        if remote_branch.base == local_branch.base:
4579
4365
            remote_branch = local_branch
4580
4366
        else:
4581
 
            self.add_cleanup(remote_branch.lock_read().unlock)
 
4367
            remote_branch.lock_read()
 
4368
            self.add_cleanup(remote_branch.unlock)
4582
4369
 
4583
4370
        local_revid_range = _revision_range_to_revid_range(
4584
4371
            _get_revision_range(my_revision, local_branch,
4639
4426
            message("Branches are up to date.\n")
4640
4427
        self.cleanup_now()
4641
4428
        if not status_code and parent is None and other_branch is not None:
4642
 
            self.add_cleanup(local_branch.lock_write().unlock)
 
4429
            local_branch.lock_write()
 
4430
            self.add_cleanup(local_branch.unlock)
4643
4431
            # handle race conditions - a parent might be set while we run.
4644
4432
            if local_branch.get_parent() is None:
4645
4433
                local_branch.set_parent(remote_branch.base)
4647
4435
 
4648
4436
 
4649
4437
class cmd_pack(Command):
4650
 
    __doc__ = """Compress the data within a repository.
4651
 
 
4652
 
    This operation compresses the data within a bazaar repository. As
4653
 
    bazaar supports automatic packing of repository, this operation is
4654
 
    normally not required to be done manually.
4655
 
 
4656
 
    During the pack operation, bazaar takes a backup of existing repository
4657
 
    data, i.e. pack files. This backup is eventually removed by bazaar
4658
 
    automatically when it is safe to do so. To save disk space by removing
4659
 
    the backed up pack files, the --clean-obsolete-packs option may be
4660
 
    used.
4661
 
 
4662
 
    Warning: If you use --clean-obsolete-packs and your machine crashes
4663
 
    during or immediately after repacking, you may be left with a state
4664
 
    where the deletion has been written to disk but the new packs have not
4665
 
    been. In this case the repository may be unusable.
4666
 
    """
 
4438
    """Compress the data within a repository."""
4667
4439
 
4668
4440
    _see_also = ['repositories']
4669
4441
    takes_args = ['branch_or_repo?']
4670
 
    takes_options = [
4671
 
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4672
 
        ]
4673
4442
 
4674
 
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
 
4443
    def run(self, branch_or_repo='.'):
4675
4444
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4676
4445
        try:
4677
4446
            branch = dir.open_branch()
4678
4447
            repository = branch.repository
4679
4448
        except errors.NotBranchError:
4680
4449
            repository = dir.open_repository()
4681
 
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
4450
        repository.pack()
4682
4451
 
4683
4452
 
4684
4453
class cmd_plugins(Command):
4685
 
    __doc__ = """List the installed plugins.
 
4454
    """List the installed plugins.
4686
4455
 
4687
4456
    This command displays the list of installed plugins including
4688
4457
    version of plugin and a short description of each.
4704
4473
 
4705
4474
    @display_command
4706
4475
    def run(self, verbose=False):
4707
 
        from bzrlib import plugin
4708
 
        # Don't give writelines a generator as some codecs don't like that
4709
 
        self.outf.writelines(
4710
 
            list(plugin.describe_plugins(show_paths=verbose)))
 
4476
        import bzrlib.plugin
 
4477
        from inspect import getdoc
 
4478
        result = []
 
4479
        for name, plugin in bzrlib.plugin.plugins().items():
 
4480
            version = plugin.__version__
 
4481
            if version == 'unknown':
 
4482
                version = ''
 
4483
            name_ver = '%s %s' % (name, version)
 
4484
            d = getdoc(plugin.module)
 
4485
            if d:
 
4486
                doc = d.split('\n')[0]
 
4487
            else:
 
4488
                doc = '(no description)'
 
4489
            result.append((name_ver, doc, plugin.path()))
 
4490
        for name_ver, doc, path in sorted(result):
 
4491
            self.outf.write("%s\n" % name_ver)
 
4492
            self.outf.write("   %s\n" % doc)
 
4493
            if verbose:
 
4494
                self.outf.write("   %s\n" % path)
 
4495
            self.outf.write("\n")
4711
4496
 
4712
4497
 
4713
4498
class cmd_testament(Command):
4714
 
    __doc__ = """Show testament (signing-form) of a revision."""
 
4499
    """Show testament (signing-form) of a revision."""
4715
4500
    takes_options = [
4716
4501
            'revision',
4717
4502
            Option('long', help='Produce long-format testament.'),
4718
4503
            Option('strict',
4719
4504
                   help='Produce a strict-format testament.')]
4720
4505
    takes_args = ['branch?']
4721
 
    encoding_type = 'exact'
4722
4506
    @display_command
4723
4507
    def run(self, branch=u'.', revision=None, long=False, strict=False):
4724
4508
        from bzrlib.testament import Testament, StrictTestament
4730
4514
            b = Branch.open_containing(branch)[0]
4731
4515
        else:
4732
4516
            b = Branch.open(branch)
4733
 
        self.add_cleanup(b.lock_read().unlock)
 
4517
        b.lock_read()
 
4518
        self.add_cleanup(b.unlock)
4734
4519
        if revision is None:
4735
4520
            rev_id = b.last_revision()
4736
4521
        else:
4737
4522
            rev_id = revision[0].as_revision_id(b)
4738
4523
        t = testament_class.from_revision(b.repository, rev_id)
4739
4524
        if long:
4740
 
            self.outf.writelines(t.as_text_lines())
 
4525
            sys.stdout.writelines(t.as_text_lines())
4741
4526
        else:
4742
 
            self.outf.write(t.as_short_text())
 
4527
            sys.stdout.write(t.as_short_text())
4743
4528
 
4744
4529
 
4745
4530
class cmd_annotate(Command):
4746
 
    __doc__ = """Show the origin of each line in a file.
 
4531
    """Show the origin of each line in a file.
4747
4532
 
4748
4533
    This prints out the given file with an annotation on the left side
4749
4534
    indicating which revision, author and date introduced the change.
4760
4545
                     Option('long', help='Show commit date in annotations.'),
4761
4546
                     'revision',
4762
4547
                     'show-ids',
4763
 
                     'directory',
4764
4548
                     ]
4765
4549
    encoding_type = 'exact'
4766
4550
 
4767
4551
    @display_command
4768
4552
    def run(self, filename, all=False, long=False, revision=None,
4769
 
            show_ids=False, directory=None):
4770
 
        from bzrlib.annotate import (
4771
 
            annotate_file_tree,
4772
 
            )
 
4553
            show_ids=False):
 
4554
        from bzrlib.annotate import annotate_file, annotate_file_tree
4773
4555
        wt, branch, relpath = \
4774
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4556
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
4775
4557
        if wt is not None:
4776
 
            self.add_cleanup(wt.lock_read().unlock)
 
4558
            wt.lock_read()
 
4559
            self.add_cleanup(wt.unlock)
4777
4560
        else:
4778
 
            self.add_cleanup(branch.lock_read().unlock)
 
4561
            branch.lock_read()
 
4562
            self.add_cleanup(branch.unlock)
4779
4563
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4780
 
        self.add_cleanup(tree.lock_read().unlock)
4781
 
        if wt is not None and revision is None:
 
4564
        tree.lock_read()
 
4565
        self.add_cleanup(tree.unlock)
 
4566
        if wt is not None:
4782
4567
            file_id = wt.path2id(relpath)
4783
4568
        else:
4784
4569
            file_id = tree.path2id(relpath)
4785
4570
        if file_id is None:
4786
4571
            raise errors.NotVersionedError(filename)
 
4572
        file_version = tree.inventory[file_id].revision
4787
4573
        if wt is not None and revision is None:
4788
4574
            # If there is a tree and we're not annotating historical
4789
4575
            # versions, annotate the working tree's content.
4790
4576
            annotate_file_tree(wt, file_id, self.outf, long, all,
4791
4577
                show_ids=show_ids)
4792
4578
        else:
4793
 
            annotate_file_tree(tree, file_id, self.outf, long, all,
4794
 
                show_ids=show_ids, branch=branch)
 
4579
            annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4580
                          show_ids=show_ids)
4795
4581
 
4796
4582
 
4797
4583
class cmd_re_sign(Command):
4798
 
    __doc__ = """Create a digital signature for an existing revision."""
 
4584
    """Create a digital signature for an existing revision."""
4799
4585
    # TODO be able to replace existing ones.
4800
4586
 
4801
4587
    hidden = True # is this right ?
4802
4588
    takes_args = ['revision_id*']
4803
 
    takes_options = ['directory', 'revision']
 
4589
    takes_options = ['revision']
4804
4590
 
4805
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
4591
    def run(self, revision_id_list=None, revision=None):
4806
4592
        if revision_id_list is not None and revision is not None:
4807
4593
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4808
4594
        if revision_id_list is None and revision is None:
4809
4595
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4810
 
        b = WorkingTree.open_containing(directory)[0].branch
4811
 
        self.add_cleanup(b.lock_write().unlock)
 
4596
        b = WorkingTree.open_containing(u'.')[0].branch
 
4597
        b.lock_write()
 
4598
        self.add_cleanup(b.unlock)
4812
4599
        return self._run(b, revision_id_list, revision)
4813
4600
 
4814
4601
    def _run(self, b, revision_id_list, revision):
4860
4647
 
4861
4648
 
4862
4649
class cmd_bind(Command):
4863
 
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
4864
 
    If no branch is supplied, rebind to the last bound location.
 
4650
    """Convert the current branch into a checkout of the supplied branch.
4865
4651
 
4866
4652
    Once converted into a checkout, commits must succeed on the master branch
4867
4653
    before they will be applied to the local branch.
4873
4659
 
4874
4660
    _see_also = ['checkouts', 'unbind']
4875
4661
    takes_args = ['location?']
4876
 
    takes_options = ['directory']
 
4662
    takes_options = []
4877
4663
 
4878
 
    def run(self, location=None, directory=u'.'):
4879
 
        b, relpath = Branch.open_containing(directory)
 
4664
    def run(self, location=None):
 
4665
        b, relpath = Branch.open_containing(u'.')
4880
4666
        if location is None:
4881
4667
            try:
4882
4668
                location = b.get_old_bound_location()
4901
4687
 
4902
4688
 
4903
4689
class cmd_unbind(Command):
4904
 
    __doc__ = """Convert the current checkout into a regular branch.
 
4690
    """Convert the current checkout into a regular branch.
4905
4691
 
4906
4692
    After unbinding, the local branch is considered independent and subsequent
4907
4693
    commits will be local only.
4909
4695
 
4910
4696
    _see_also = ['checkouts', 'bind']
4911
4697
    takes_args = []
4912
 
    takes_options = ['directory']
 
4698
    takes_options = []
4913
4699
 
4914
 
    def run(self, directory=u'.'):
4915
 
        b, relpath = Branch.open_containing(directory)
 
4700
    def run(self):
 
4701
        b, relpath = Branch.open_containing(u'.')
4916
4702
        if not b.unbind():
4917
4703
            raise errors.BzrCommandError('Local branch is not bound')
4918
4704
 
4919
4705
 
4920
4706
class cmd_uncommit(Command):
4921
 
    __doc__ = """Remove the last committed revision.
 
4707
    """Remove the last committed revision.
4922
4708
 
4923
4709
    --verbose will print out what is being removed.
4924
4710
    --dry-run will go through all the motions, but not actually
4964
4750
            b = control.open_branch()
4965
4751
 
4966
4752
        if tree is not None:
4967
 
            self.add_cleanup(tree.lock_write().unlock)
 
4753
            tree.lock_write()
 
4754
            self.add_cleanup(tree.unlock)
4968
4755
        else:
4969
 
            self.add_cleanup(b.lock_write().unlock)
 
4756
            b.lock_write()
 
4757
            self.add_cleanup(b.unlock)
4970
4758
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4971
4759
 
4972
4760
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
5011
4799
            self.outf.write('The above revision(s) will be removed.\n')
5012
4800
 
5013
4801
        if not force:
5014
 
            if not ui.ui_factory.confirm_action(
5015
 
                    u'Uncommit these revisions',
5016
 
                    'bzrlib.builtins.uncommit',
5017
 
                    {}):
5018
 
                self.outf.write('Canceled\n')
 
4802
            if not ui.ui_factory.get_boolean('Are you sure'):
 
4803
                self.outf.write('Canceled')
5019
4804
                return 0
5020
4805
 
5021
4806
        mutter('Uncommitting from {%s} to {%s}',
5027
4812
 
5028
4813
 
5029
4814
class cmd_break_lock(Command):
5030
 
    __doc__ = """Break a dead lock.
5031
 
 
5032
 
    This command breaks a lock on a repository, branch, working directory or
5033
 
    config file.
 
4815
    """Break a dead lock on a repository, branch or working directory.
5034
4816
 
5035
4817
    CAUTION: Locks should only be broken when you are sure that the process
5036
4818
    holding the lock has been stopped.
5041
4823
    :Examples:
5042
4824
        bzr break-lock
5043
4825
        bzr break-lock bzr+ssh://example.com/bzr/foo
5044
 
        bzr break-lock --conf ~/.bazaar
5045
4826
    """
5046
 
 
5047
4827
    takes_args = ['location?']
5048
 
    takes_options = [
5049
 
        Option('config',
5050
 
               help='LOCATION is the directory where the config lock is.'),
5051
 
        Option('force',
5052
 
            help='Do not ask for confirmation before breaking the lock.'),
5053
 
        ]
5054
4828
 
5055
 
    def run(self, location=None, config=False, force=False):
 
4829
    def run(self, location=None, show=False):
5056
4830
        if location is None:
5057
4831
            location = u'.'
5058
 
        if force:
5059
 
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5060
 
                None,
5061
 
                {'bzrlib.lockdir.break': True})
5062
 
        if config:
5063
 
            conf = _mod_config.LockableConfig(file_name=location)
5064
 
            conf.break_lock()
5065
 
        else:
5066
 
            control, relpath = bzrdir.BzrDir.open_containing(location)
5067
 
            try:
5068
 
                control.break_lock()
5069
 
            except NotImplementedError:
5070
 
                pass
 
4832
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4833
        try:
 
4834
            control.break_lock()
 
4835
        except NotImplementedError:
 
4836
            pass
5071
4837
 
5072
4838
 
5073
4839
class cmd_wait_until_signalled(Command):
5074
 
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4840
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
5075
4841
 
5076
4842
    This just prints a line to signal when it is ready, then blocks on stdin.
5077
4843
    """
5085
4851
 
5086
4852
 
5087
4853
class cmd_serve(Command):
5088
 
    __doc__ = """Run the bzr server."""
 
4854
    """Run the bzr server."""
5089
4855
 
5090
4856
    aliases = ['server']
5091
4857
 
5102
4868
                    'result in a dynamically allocated port.  The default port '
5103
4869
                    'depends on the protocol.',
5104
4870
               type=str),
5105
 
        custom_help('directory',
5106
 
               help='Serve contents of this directory.'),
 
4871
        Option('directory',
 
4872
               help='Serve contents of this directory.',
 
4873
               type=unicode),
5107
4874
        Option('allow-writes',
5108
4875
               help='By default the server is a readonly server.  Supplying '
5109
4876
                    '--allow-writes enables write access to the contents of '
5136
4903
 
5137
4904
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
5138
4905
            protocol=None):
5139
 
        from bzrlib import transport
 
4906
        from bzrlib.transport import get_transport, transport_server_registry
5140
4907
        if directory is None:
5141
4908
            directory = os.getcwd()
5142
4909
        if protocol is None:
5143
 
            protocol = transport.transport_server_registry.get()
 
4910
            protocol = transport_server_registry.get()
5144
4911
        host, port = self.get_host_and_port(port)
5145
4912
        url = urlutils.local_path_to_url(directory)
5146
4913
        if not allow_writes:
5147
4914
            url = 'readonly+' + url
5148
 
        t = transport.get_transport(url)
5149
 
        protocol(t, host, port, inet)
 
4915
        transport = get_transport(url)
 
4916
        protocol(transport, host, port, inet)
5150
4917
 
5151
4918
 
5152
4919
class cmd_join(Command):
5153
 
    __doc__ = """Combine a tree into its containing tree.
 
4920
    """Combine a tree into its containing tree.
5154
4921
 
5155
4922
    This command requires the target tree to be in a rich-root format.
5156
4923
 
5158
4925
    not part of it.  (Such trees can be produced by "bzr split", but also by
5159
4926
    running "bzr branch" with the target inside a tree.)
5160
4927
 
5161
 
    The result is a combined tree, with the subtree no longer an independent
 
4928
    The result is a combined tree, with the subtree no longer an independant
5162
4929
    part.  This is marked as a merge of the subtree into the containing tree,
5163
4930
    and all history is preserved.
5164
4931
    """
5196
4963
 
5197
4964
 
5198
4965
class cmd_split(Command):
5199
 
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
4966
    """Split a subdirectory of a tree into a separate tree.
5200
4967
 
5201
4968
    This command will produce a target tree in a format that supports
5202
4969
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
5222
4989
 
5223
4990
 
5224
4991
class cmd_merge_directive(Command):
5225
 
    __doc__ = """Generate a merge directive for auto-merge tools.
 
4992
    """Generate a merge directive for auto-merge tools.
5226
4993
 
5227
4994
    A directive requests a merge to be performed, and also provides all the
5228
4995
    information necessary to do so.  This means it must either include a
5245
5012
    _see_also = ['send']
5246
5013
 
5247
5014
    takes_options = [
5248
 
        'directory',
5249
5015
        RegistryOption.from_kwargs('patch-type',
5250
5016
            'The type of patch to include in the directive.',
5251
5017
            title='Patch type',
5264
5030
    encoding_type = 'exact'
5265
5031
 
5266
5032
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5267
 
            sign=False, revision=None, mail_to=None, message=None,
5268
 
            directory=u'.'):
 
5033
            sign=False, revision=None, mail_to=None, message=None):
5269
5034
        from bzrlib.revision import ensure_null, NULL_REVISION
5270
5035
        include_patch, include_bundle = {
5271
5036
            'plain': (False, False),
5272
5037
            'diff': (True, False),
5273
5038
            'bundle': (True, True),
5274
5039
            }[patch_type]
5275
 
        branch = Branch.open(directory)
 
5040
        branch = Branch.open('.')
5276
5041
        stored_submit_branch = branch.get_submit_branch()
5277
5042
        if submit_branch is None:
5278
5043
            submit_branch = stored_submit_branch
5323
5088
 
5324
5089
 
5325
5090
class cmd_send(Command):
5326
 
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
5091
    """Mail or create a merge-directive for submitting changes.
5327
5092
 
5328
5093
    A merge directive provides many things needed for requesting merges:
5329
5094
 
5354
5119
    source branch defaults to that containing the working directory, but can
5355
5120
    be changed using --from.
5356
5121
 
5357
 
    Both the submit branch and the public branch follow the usual behavior with
5358
 
    respect to --remember: If there is no default location set, the first send
5359
 
    will set it (use --no-remember to avoid settting it). After that, you can
5360
 
    omit the location to use the default.  To change the default, use
5361
 
    --remember. The value will only be saved if the location can be accessed.
5362
 
 
5363
5122
    In order to calculate those changes, bzr must analyse the submit branch.
5364
5123
    Therefore it is most efficient for the submit branch to be a local mirror.
5365
5124
    If a public location is known for the submit_branch, that location is used
5369
5128
    given, in which case it is sent to a file.
5370
5129
 
5371
5130
    Mail is sent using your preferred mail program.  This should be transparent
5372
 
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
5131
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
5373
5132
    If the preferred client can't be found (or used), your editor will be used.
5374
5133
 
5375
5134
    To use a specific mail program, set the mail_client configuration option.
5434
5193
        ]
5435
5194
 
5436
5195
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5437
 
            no_patch=False, revision=None, remember=None, output=None,
 
5196
            no_patch=False, revision=None, remember=False, output=None,
5438
5197
            format=None, mail_to=None, message=None, body=None,
5439
5198
            strict=None, **kwargs):
5440
5199
        from bzrlib.send import send
5446
5205
 
5447
5206
 
5448
5207
class cmd_bundle_revisions(cmd_send):
5449
 
    __doc__ = """Create a merge-directive for submitting changes.
 
5208
    """Create a merge-directive for submitting changes.
5450
5209
 
5451
5210
    A merge directive provides many things needed for requesting merges:
5452
5211
 
5519
5278
 
5520
5279
 
5521
5280
class cmd_tag(Command):
5522
 
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5281
    """Create, remove or modify a tag naming a revision.
5523
5282
 
5524
5283
    Tags give human-meaningful names to revisions.  Commands that take a -r
5525
5284
    (--revision) option can be given -rtag:X, where X is any previously
5546
5305
        Option('delete',
5547
5306
            help='Delete this tag rather than placing it.',
5548
5307
            ),
5549
 
        custom_help('directory',
5550
 
            help='Branch in which to place the tag.'),
 
5308
        Option('directory',
 
5309
            help='Branch in which to place the tag.',
 
5310
            short_name='d',
 
5311
            type=unicode,
 
5312
            ),
5551
5313
        Option('force',
5552
5314
            help='Replace existing tags.',
5553
5315
            ),
5561
5323
            revision=None,
5562
5324
            ):
5563
5325
        branch, relpath = Branch.open_containing(directory)
5564
 
        self.add_cleanup(branch.lock_write().unlock)
 
5326
        branch.lock_write()
 
5327
        self.add_cleanup(branch.unlock)
5565
5328
        if delete:
5566
5329
            if tag_name is None:
5567
5330
                raise errors.BzrCommandError("No tag specified to delete.")
5568
5331
            branch.tags.delete_tag(tag_name)
5569
 
            note('Deleted tag %s.' % tag_name)
 
5332
            self.outf.write('Deleted tag %s.\n' % tag_name)
5570
5333
        else:
5571
5334
            if revision:
5572
5335
                if len(revision) != 1:
5584
5347
            if (not force) and branch.tags.has_tag(tag_name):
5585
5348
                raise errors.TagAlreadyExists(tag_name)
5586
5349
            branch.tags.set_tag(tag_name, revision_id)
5587
 
            note('Created tag %s.' % tag_name)
 
5350
            self.outf.write('Created tag %s.\n' % tag_name)
5588
5351
 
5589
5352
 
5590
5353
class cmd_tags(Command):
5591
 
    __doc__ = """List tags.
 
5354
    """List tags.
5592
5355
 
5593
5356
    This command shows a table of tag names and the revisions they reference.
5594
5357
    """
5595
5358
 
5596
5359
    _see_also = ['tag']
5597
5360
    takes_options = [
5598
 
        custom_help('directory',
5599
 
            help='Branch whose tags should be displayed.'),
5600
 
        RegistryOption('sort',
 
5361
        Option('directory',
 
5362
            help='Branch whose tags should be displayed.',
 
5363
            short_name='d',
 
5364
            type=unicode,
 
5365
            ),
 
5366
        RegistryOption.from_kwargs('sort',
5601
5367
            'Sort tags by different criteria.', title='Sorting',
5602
 
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
 
5368
            alpha='Sort tags lexicographically (default).',
 
5369
            time='Sort tags chronologically.',
5603
5370
            ),
5604
5371
        'show-ids',
5605
5372
        'revision',
5606
5373
    ]
5607
5374
 
5608
5375
    @display_command
5609
 
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
5610
 
        from bzrlib.tag import tag_sort_methods
 
5376
    def run(self,
 
5377
            directory='.',
 
5378
            sort='alpha',
 
5379
            show_ids=False,
 
5380
            revision=None,
 
5381
            ):
5611
5382
        branch, relpath = Branch.open_containing(directory)
5612
5383
 
5613
5384
        tags = branch.tags.get_tag_dict().items()
5614
5385
        if not tags:
5615
5386
            return
5616
5387
 
5617
 
        self.add_cleanup(branch.lock_read().unlock)
 
5388
        branch.lock_read()
 
5389
        self.add_cleanup(branch.unlock)
5618
5390
        if revision:
5619
 
            # Restrict to the specified range
5620
 
            tags = self._tags_for_range(branch, revision)
5621
 
        if sort is None:
5622
 
            sort = tag_sort_methods.get()
5623
 
        sort(branch, tags)
 
5391
            graph = branch.repository.get_graph()
 
5392
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5393
            revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5394
            # only show revisions between revid1 and revid2 (inclusive)
 
5395
            tags = [(tag, revid) for tag, revid in tags if
 
5396
                graph.is_between(revid, revid1, revid2)]
 
5397
        if sort == 'alpha':
 
5398
            tags.sort()
 
5399
        elif sort == 'time':
 
5400
            timestamps = {}
 
5401
            for tag, revid in tags:
 
5402
                try:
 
5403
                    revobj = branch.repository.get_revision(revid)
 
5404
                except errors.NoSuchRevision:
 
5405
                    timestamp = sys.maxint # place them at the end
 
5406
                else:
 
5407
                    timestamp = revobj.timestamp
 
5408
                timestamps[revid] = timestamp
 
5409
            tags.sort(key=lambda x: timestamps[x[1]])
5624
5410
        if not show_ids:
5625
5411
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5626
5412
            for index, (tag, revid) in enumerate(tags):
5628
5414
                    revno = branch.revision_id_to_dotted_revno(revid)
5629
5415
                    if isinstance(revno, tuple):
5630
5416
                        revno = '.'.join(map(str, revno))
5631
 
                except (errors.NoSuchRevision, errors.GhostRevisionsHaveNoRevno):
 
5417
                except errors.NoSuchRevision:
5632
5418
                    # Bad tag data/merges can lead to tagged revisions
5633
5419
                    # which are not in this branch. Fail gracefully ...
5634
5420
                    revno = '?'
5637
5423
        for tag, revspec in tags:
5638
5424
            self.outf.write('%-20s %s\n' % (tag, revspec))
5639
5425
 
5640
 
    def _tags_for_range(self, branch, revision):
5641
 
        range_valid = True
5642
 
        rev1, rev2 = _get_revision_range(revision, branch, self.name())
5643
 
        revid1, revid2 = rev1.rev_id, rev2.rev_id
5644
 
        # _get_revision_range will always set revid2 if it's not specified.
5645
 
        # If revid1 is None, it means we want to start from the branch
5646
 
        # origin which is always a valid ancestor. If revid1 == revid2, the
5647
 
        # ancestry check is useless.
5648
 
        if revid1 and revid1 != revid2:
5649
 
            # FIXME: We really want to use the same graph than
5650
 
            # branch.iter_merge_sorted_revisions below, but this is not
5651
 
            # easily available -- vila 2011-09-23
5652
 
            if branch.repository.get_graph().is_ancestor(revid2, revid1):
5653
 
                # We don't want to output anything in this case...
5654
 
                return []
5655
 
        # only show revisions between revid1 and revid2 (inclusive)
5656
 
        tagged_revids = branch.tags.get_reverse_tag_dict()
5657
 
        found = []
5658
 
        for r in branch.iter_merge_sorted_revisions(
5659
 
            start_revision_id=revid2, stop_revision_id=revid1,
5660
 
            stop_rule='include'):
5661
 
            revid_tags = tagged_revids.get(r[0], None)
5662
 
            if revid_tags:
5663
 
                found.extend([(tag, r[0]) for tag in revid_tags])
5664
 
        return found
5665
 
 
5666
5426
 
5667
5427
class cmd_reconfigure(Command):
5668
 
    __doc__ = """Reconfigure the type of a bzr directory.
 
5428
    """Reconfigure the type of a bzr directory.
5669
5429
 
5670
5430
    A target configuration must be specified.
5671
5431
 
5718
5478
            unstacked=None):
5719
5479
        directory = bzrdir.BzrDir.open(location)
5720
5480
        if stacked_on and unstacked:
5721
 
            raise errors.BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5481
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5722
5482
        elif stacked_on is not None:
5723
5483
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5724
5484
        elif unstacked:
5756
5516
 
5757
5517
 
5758
5518
class cmd_switch(Command):
5759
 
    __doc__ = """Set the branch of a checkout and update.
 
5519
    """Set the branch of a checkout and update.
5760
5520
 
5761
5521
    For lightweight checkouts, this changes the branch being referenced.
5762
5522
    For heavyweight checkouts, this checks that there are no local commits
5779
5539
    """
5780
5540
 
5781
5541
    takes_args = ['to_location?']
5782
 
    takes_options = ['directory',
5783
 
                     Option('force',
 
5542
    takes_options = [Option('force',
5784
5543
                        help='Switch even if local commits will be lost.'),
5785
5544
                     'revision',
5786
5545
                     Option('create-branch', short_name='b',
5789
5548
                    ]
5790
5549
 
5791
5550
    def run(self, to_location=None, force=False, create_branch=False,
5792
 
            revision=None, directory=u'.'):
 
5551
            revision=None):
5793
5552
        from bzrlib import switch
5794
 
        tree_location = directory
 
5553
        tree_location = '.'
5795
5554
        revision = _get_one_revision('switch', revision)
5796
5555
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5797
5556
        if to_location is None:
5798
5557
            if revision is None:
5799
5558
                raise errors.BzrCommandError('You must supply either a'
5800
5559
                                             ' revision or a location')
5801
 
            to_location = tree_location
 
5560
            to_location = '.'
5802
5561
        try:
5803
5562
            branch = control_dir.open_branch()
5804
5563
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5853
5612
 
5854
5613
 
5855
5614
class cmd_view(Command):
5856
 
    __doc__ = """Manage filtered views.
 
5615
    """Manage filtered views.
5857
5616
 
5858
5617
    Views provide a mask over the tree so that users can focus on
5859
5618
    a subset of a tree when doing their work. After creating a view,
5939
5698
            name=None,
5940
5699
            switch=None,
5941
5700
            ):
5942
 
        tree, file_list = WorkingTree.open_containing_paths(file_list,
5943
 
            apply_view=False)
 
5701
        tree, file_list = tree_files(file_list, apply_view=False)
5944
5702
        current_view, view_dict = tree.views.get_view_info()
5945
5703
        if name is None:
5946
5704
            name = current_view
6008
5766
 
6009
5767
 
6010
5768
class cmd_hooks(Command):
6011
 
    __doc__ = """Show hooks."""
 
5769
    """Show hooks."""
6012
5770
 
6013
5771
    hidden = True
6014
5772
 
6028
5786
 
6029
5787
 
6030
5788
class cmd_remove_branch(Command):
6031
 
    __doc__ = """Remove a branch.
 
5789
    """Remove a branch.
6032
5790
 
6033
5791
    This will remove the branch from the specified location but 
6034
5792
    will keep any working tree or repository in place.
6050
5808
            location = "."
6051
5809
        branch = Branch.open_containing(location)[0]
6052
5810
        branch.bzrdir.destroy_branch()
6053
 
 
 
5811
        
6054
5812
 
6055
5813
class cmd_shelve(Command):
6056
 
    __doc__ = """Temporarily set aside some changes from the current tree.
 
5814
    """Temporarily set aside some changes from the current tree.
6057
5815
 
6058
5816
    Shelve allows you to temporarily put changes you've made "on the shelf",
6059
5817
    ie. out of the way, until a later time when you can bring them back from
6075
5833
 
6076
5834
    You can put multiple items on the shelf, and by default, 'unshelve' will
6077
5835
    restore the most recently shelved changes.
6078
 
 
6079
 
    For complicated changes, it is possible to edit the changes in a separate
6080
 
    editor program to decide what the file remaining in the working copy
6081
 
    should look like.  To do this, add the configuration option
6082
 
 
6083
 
        change_editor = PROGRAM @new_path @old_path
6084
 
 
6085
 
    where @new_path is replaced with the path of the new version of the 
6086
 
    file and @old_path is replaced with the path of the old version of 
6087
 
    the file.  The PROGRAM should save the new file with the desired 
6088
 
    contents of the file in the working tree.
6089
 
        
6090
5836
    """
6091
5837
 
6092
5838
    takes_args = ['file*']
6093
5839
 
6094
5840
    takes_options = [
6095
 
        'directory',
6096
5841
        'revision',
6097
5842
        Option('all', help='Shelve all changes.'),
6098
5843
        'message',
6104
5849
        Option('destroy',
6105
5850
               help='Destroy removed changes instead of shelving them.'),
6106
5851
    ]
6107
 
    _see_also = ['unshelve', 'configuration']
 
5852
    _see_also = ['unshelve']
6108
5853
 
6109
5854
    def run(self, revision=None, all=False, file_list=None, message=None,
6110
 
            writer=None, list=False, destroy=False, directory=None):
 
5855
            writer=None, list=False, destroy=False):
6111
5856
        if list:
6112
 
            return self.run_for_list(directory=directory)
 
5857
            return self.run_for_list()
6113
5858
        from bzrlib.shelf_ui import Shelver
6114
5859
        if writer is None:
6115
5860
            writer = bzrlib.option.diff_writer_registry.get()
6116
5861
        try:
6117
5862
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6118
 
                file_list, message, destroy=destroy, directory=directory)
 
5863
                file_list, message, destroy=destroy)
6119
5864
            try:
6120
5865
                shelver.run()
6121
5866
            finally:
6123
5868
        except errors.UserAbort:
6124
5869
            return 0
6125
5870
 
6126
 
    def run_for_list(self, directory=None):
6127
 
        if directory is None:
6128
 
            directory = u'.'
6129
 
        tree = WorkingTree.open_containing(directory)[0]
6130
 
        self.add_cleanup(tree.lock_read().unlock)
 
5871
    def run_for_list(self):
 
5872
        tree = WorkingTree.open_containing('.')[0]
 
5873
        tree.lock_read()
 
5874
        self.add_cleanup(tree.unlock)
6131
5875
        manager = tree.get_shelf_manager()
6132
5876
        shelves = manager.active_shelves()
6133
5877
        if len(shelves) == 0:
6142
5886
 
6143
5887
 
6144
5888
class cmd_unshelve(Command):
6145
 
    __doc__ = """Restore shelved changes.
 
5889
    """Restore shelved changes.
6146
5890
 
6147
5891
    By default, the most recently shelved changes are restored. However if you
6148
5892
    specify a shelf by id those changes will be restored instead.  This works
6151
5895
 
6152
5896
    takes_args = ['shelf_id?']
6153
5897
    takes_options = [
6154
 
        'directory',
6155
5898
        RegistryOption.from_kwargs(
6156
5899
            'action', help="The action to perform.",
6157
5900
            enum_switch=False, value_switches=True,
6165
5908
    ]
6166
5909
    _see_also = ['shelve']
6167
5910
 
6168
 
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
5911
    def run(self, shelf_id=None, action='apply'):
6169
5912
        from bzrlib.shelf_ui import Unshelver
6170
 
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
5913
        unshelver = Unshelver.from_args(shelf_id, action)
6171
5914
        try:
6172
5915
            unshelver.run()
6173
5916
        finally:
6175
5918
 
6176
5919
 
6177
5920
class cmd_clean_tree(Command):
6178
 
    __doc__ = """Remove unwanted files from working tree.
 
5921
    """Remove unwanted files from working tree.
6179
5922
 
6180
5923
    By default, only unknown files, not ignored files, are deleted.  Versioned
6181
5924
    files are never deleted.
6189
5932
 
6190
5933
    To check what clean-tree will do, use --dry-run.
6191
5934
    """
6192
 
    takes_options = ['directory',
6193
 
                     Option('ignored', help='Delete all ignored files.'),
6194
 
                     Option('detritus', help='Delete conflict files, merge and revert'
 
5935
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5936
                     Option('detritus', help='Delete conflict files, merge'
6195
5937
                            ' backups, and failed selftest dirs.'),
6196
5938
                     Option('unknown',
6197
5939
                            help='Delete files unknown to bzr (default).'),
6199
5941
                            ' deleting them.'),
6200
5942
                     Option('force', help='Do not prompt before deleting.')]
6201
5943
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6202
 
            force=False, directory=u'.'):
 
5944
            force=False):
6203
5945
        from bzrlib.clean_tree import clean_tree
6204
5946
        if not (unknown or ignored or detritus):
6205
5947
            unknown = True
6206
5948
        if dry_run:
6207
5949
            force = True
6208
 
        clean_tree(directory, unknown=unknown, ignored=ignored,
6209
 
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5950
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5951
                   dry_run=dry_run, no_prompt=force)
6210
5952
 
6211
5953
 
6212
5954
class cmd_reference(Command):
6213
 
    __doc__ = """list, view and set branch locations for nested trees.
 
5955
    """list, view and set branch locations for nested trees.
6214
5956
 
6215
5957
    If no arguments are provided, lists the branch locations for nested trees.
6216
5958
    If one argument is provided, display the branch location for that tree.
6256
5998
            self.outf.write('%s %s\n' % (path, location))
6257
5999
 
6258
6000
 
6259
 
class cmd_export_pot(Command):
6260
 
    __doc__ = """Export command helps and error messages in po format."""
6261
 
 
6262
 
    hidden = True
6263
 
 
6264
 
    def run(self):
6265
 
        from bzrlib.export_pot import export_pot
6266
 
        export_pot(self.outf)
6267
 
 
6268
 
 
6269
6001
def _register_lazy_builtins():
6270
6002
    # register lazy builtins from other modules; called at startup and should
6271
6003
    # be only called once.
6272
6004
    for (name, aliases, module_name) in [
6273
6005
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6274
 
        ('cmd_config', [], 'bzrlib.config'),
6275
6006
        ('cmd_dpush', [], 'bzrlib.foreign'),
6276
6007
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6277
6008
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6278
6009
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6279
 
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6280
 
        ('cmd_verify_signatures', [],
6281
 
                                        'bzrlib.commit_signature_commands'),
6282
 
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
 
6010
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6283
6011
        ]:
6284
6012
        builtin_command_registry.register_lazy(name, aliases, module_name)