/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Marco Pantaleoni
  • Date: 2010-03-25 14:22:41 UTC
  • mto: This revision was merged to the branch mainline in revision 5174.
  • Revision ID: panta@elasticworld.org-20100325142241-vtl1hshva7uiz3ap
Applied suggestions from merge reviewer (John A Meinel):

- removed duplication of checks for presence of hooks.
- adapted to bazaar style guideline
- simplified test cases callback

Show diffs side-by-side

added added

removed removed

Lines of Context:
60
60
from bzrlib.workingtree import WorkingTree
61
61
""")
62
62
 
63
 
from bzrlib.commands import (
64
 
    Command,
65
 
    builtin_command_registry,
66
 
    display_command,
67
 
    )
 
63
from bzrlib.commands import Command, display_command
68
64
from bzrlib.option import (
69
65
    ListOption,
70
66
    Option,
180
176
                view_str = views.view_display_str(view_files)
181
177
                note("Ignoring files outside view. View is %s" % view_str)
182
178
        return tree, file_list
183
 
    tree = WorkingTree.open_containing(file_list[0])[0]
 
179
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
184
180
    return tree, safe_relpath_files(tree, file_list, canonicalize,
185
181
        apply_view=apply_view)
186
182
 
232
228
    return view_info
233
229
 
234
230
 
235
 
def _open_directory_or_containing_tree_or_branch(filename, directory):
236
 
    """Open the tree or branch containing the specified file, unless
237
 
    the --directory option is used to specify a different branch."""
238
 
    if directory is not None:
239
 
        return (None, Branch.open(directory), filename)
240
 
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
241
 
 
242
 
 
243
231
# TODO: Make sure no commands unconditionally use the working directory as a
244
232
# branch.  If a filename argument is used, the first of them should be used to
245
233
# specify the branch.  (Perhaps this can be factored out into some kind of
247
235
# opens the branch?)
248
236
 
249
237
class cmd_status(Command):
250
 
    __doc__ = """Display status summary.
 
238
    """Display status summary.
251
239
 
252
240
    This reports on versioned and unknown files, reporting them
253
241
    grouped by state.  Possible states are:
340
328
 
341
329
 
342
330
class cmd_cat_revision(Command):
343
 
    __doc__ = """Write out metadata for a revision.
 
331
    """Write out metadata for a revision.
344
332
 
345
333
    The revision to print can either be specified by a specific
346
334
    revision identifier, or you can use --revision.
348
336
 
349
337
    hidden = True
350
338
    takes_args = ['revision_id?']
351
 
    takes_options = ['directory', 'revision']
 
339
    takes_options = ['revision']
352
340
    # cat-revision is more for frontends so should be exact
353
341
    encoding = 'strict'
354
342
 
361
349
        self.outf.write(revtext.decode('utf-8'))
362
350
 
363
351
    @display_command
364
 
    def run(self, revision_id=None, revision=None, directory=u'.'):
 
352
    def run(self, revision_id=None, revision=None):
365
353
        if revision_id is not None and revision is not None:
366
354
            raise errors.BzrCommandError('You can only supply one of'
367
355
                                         ' revision_id or --revision')
368
356
        if revision_id is None and revision is None:
369
357
            raise errors.BzrCommandError('You must supply either'
370
358
                                         ' --revision or a revision_id')
371
 
        b = WorkingTree.open_containing(directory)[0].branch
 
359
        b = WorkingTree.open_containing(u'.')[0].branch
372
360
 
373
361
        revisions = b.repository.revisions
374
362
        if revisions is None:
398
386
        
399
387
 
400
388
class cmd_dump_btree(Command):
401
 
    __doc__ = """Dump the contents of a btree index file to stdout.
 
389
    """Dump the contents of a btree index file to stdout.
402
390
 
403
391
    PATH is a btree index file, it can be any URL. This includes things like
404
392
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
479
467
 
480
468
 
481
469
class cmd_remove_tree(Command):
482
 
    __doc__ = """Remove the working tree from a given branch/checkout.
 
470
    """Remove the working tree from a given branch/checkout.
483
471
 
484
472
    Since a lightweight checkout is little more than a working tree
485
473
    this will refuse to run against one.
491
479
    takes_options = [
492
480
        Option('force',
493
481
               help='Remove the working tree even if it has '
494
 
                    'uncommitted or shelved changes.'),
 
482
                    'uncommitted changes.'),
495
483
        ]
496
484
 
497
485
    def run(self, location_list, force=False):
511
499
            if not force:
512
500
                if (working.has_changes()):
513
501
                    raise errors.UncommittedChanges(working)
514
 
                if working.get_shelf_manager().last_shelf() is not None:
515
 
                    raise errors.ShelvedChanges(working)
516
502
 
517
 
            if working.user_url != working.branch.user_url:
 
503
            working_path = working.bzrdir.root_transport.base
 
504
            branch_path = working.branch.bzrdir.root_transport.base
 
505
            if working_path != branch_path:
518
506
                raise errors.BzrCommandError("You cannot remove the working tree"
519
507
                                             " from a lightweight checkout")
520
508
 
522
510
 
523
511
 
524
512
class cmd_revno(Command):
525
 
    __doc__ = """Show current revision number.
 
513
    """Show current revision number.
526
514
 
527
515
    This is equal to the number of revisions on this branch.
528
516
    """
538
526
        if tree:
539
527
            try:
540
528
                wt = WorkingTree.open_containing(location)[0]
541
 
                self.add_cleanup(wt.lock_read().unlock)
 
529
                wt.lock_read()
542
530
            except (errors.NoWorkingTree, errors.NotLocalUrl):
543
531
                raise errors.NoWorkingTree(location)
 
532
            self.add_cleanup(wt.unlock)
544
533
            revid = wt.last_revision()
545
534
            try:
546
535
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
549
538
            revno = ".".join(str(n) for n in revno_t)
550
539
        else:
551
540
            b = Branch.open_containing(location)[0]
552
 
            self.add_cleanup(b.lock_read().unlock)
 
541
            b.lock_read()
 
542
            self.add_cleanup(b.unlock)
553
543
            revno = b.revno()
554
544
        self.cleanup_now()
555
545
        self.outf.write(str(revno) + '\n')
556
546
 
557
547
 
558
548
class cmd_revision_info(Command):
559
 
    __doc__ = """Show revision number and revision id for a given revision identifier.
 
549
    """Show revision number and revision id for a given revision identifier.
560
550
    """
561
551
    hidden = True
562
552
    takes_args = ['revision_info*']
563
553
    takes_options = [
564
554
        'revision',
565
 
        custom_help('directory',
 
555
        Option('directory',
566
556
            help='Branch to examine, '
567
 
                 'rather than the one containing the working directory.'),
 
557
                 'rather than the one containing the working directory.',
 
558
            short_name='d',
 
559
            type=unicode,
 
560
            ),
568
561
        Option('tree', help='Show revno of working tree'),
569
562
        ]
570
563
 
575
568
        try:
576
569
            wt = WorkingTree.open_containing(directory)[0]
577
570
            b = wt.branch
578
 
            self.add_cleanup(wt.lock_read().unlock)
 
571
            wt.lock_read()
 
572
            self.add_cleanup(wt.unlock)
579
573
        except (errors.NoWorkingTree, errors.NotLocalUrl):
580
574
            wt = None
581
575
            b = Branch.open_containing(directory)[0]
582
 
            self.add_cleanup(b.lock_read().unlock)
 
576
            b.lock_read()
 
577
            self.add_cleanup(b.unlock)
583
578
        revision_ids = []
584
579
        if revision is not None:
585
580
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
613
608
 
614
609
 
615
610
class cmd_add(Command):
616
 
    __doc__ = """Add specified files or directories.
 
611
    """Add specified files or directories.
617
612
 
618
613
    In non-recursive mode, all the named items are added, regardless
619
614
    of whether they were previously ignored.  A warning is given if
684
679
                should_print=(not is_quiet()))
685
680
 
686
681
        if base_tree:
687
 
            self.add_cleanup(base_tree.lock_read().unlock)
 
682
            base_tree.lock_read()
 
683
            self.add_cleanup(base_tree.unlock)
688
684
        tree, file_list = tree_files_for_add(file_list)
689
685
        added, ignored = tree.smart_add(file_list, not
690
686
            no_recurse, action=action, save=not dry_run)
698
694
 
699
695
 
700
696
class cmd_mkdir(Command):
701
 
    __doc__ = """Create a new versioned directory.
 
697
    """Create a new versioned directory.
702
698
 
703
699
    This is equivalent to creating the directory and then adding it.
704
700
    """
720
716
 
721
717
 
722
718
class cmd_relpath(Command):
723
 
    __doc__ = """Show path of a file relative to root"""
 
719
    """Show path of a file relative to root"""
724
720
 
725
721
    takes_args = ['filename']
726
722
    hidden = True
735
731
 
736
732
 
737
733
class cmd_inventory(Command):
738
 
    __doc__ = """Show inventory of the current working copy or a revision.
 
734
    """Show inventory of the current working copy or a revision.
739
735
 
740
736
    It is possible to limit the output to a particular entry
741
737
    type using the --kind option.  For example: --kind file.
762
758
 
763
759
        revision = _get_one_revision('inventory', revision)
764
760
        work_tree, file_list = tree_files(file_list)
765
 
        self.add_cleanup(work_tree.lock_read().unlock)
 
761
        work_tree.lock_read()
 
762
        self.add_cleanup(work_tree.unlock)
766
763
        if revision is not None:
767
764
            tree = revision.as_tree(work_tree.branch)
768
765
 
769
766
            extra_trees = [work_tree]
770
 
            self.add_cleanup(tree.lock_read().unlock)
 
767
            tree.lock_read()
 
768
            self.add_cleanup(tree.unlock)
771
769
        else:
772
770
            tree = work_tree
773
771
            extra_trees = []
794
792
 
795
793
 
796
794
class cmd_mv(Command):
797
 
    __doc__ = """Move or rename a file.
 
795
    """Move or rename a file.
798
796
 
799
797
    :Usage:
800
798
        bzr mv OLDNAME NEWNAME
833
831
        if len(names_list) < 2:
834
832
            raise errors.BzrCommandError("missing file argument")
835
833
        tree, rel_names = tree_files(names_list, canonicalize=False)
836
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
834
        tree.lock_tree_write()
 
835
        self.add_cleanup(tree.unlock)
837
836
        self._run(tree, names_list, rel_names, after)
838
837
 
839
838
    def run_auto(self, names_list, after, dry_run):
844
843
            raise errors.BzrCommandError('--after cannot be specified with'
845
844
                                         ' --auto.')
846
845
        work_tree, file_list = tree_files(names_list, default_branch='.')
847
 
        self.add_cleanup(work_tree.lock_tree_write().unlock)
 
846
        work_tree.lock_tree_write()
 
847
        self.add_cleanup(work_tree.unlock)
848
848
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
849
849
 
850
850
    def _run(self, tree, names_list, rel_names, after):
929
929
 
930
930
 
931
931
class cmd_pull(Command):
932
 
    __doc__ = """Turn this branch into a mirror of another branch.
 
932
    """Turn this branch into a mirror of another branch.
933
933
 
934
934
    By default, this command only works on branches that have not diverged.
935
935
    Branches are considered diverged if the destination branch's most recent 
958
958
    takes_options = ['remember', 'overwrite', 'revision',
959
959
        custom_help('verbose',
960
960
            help='Show logs of pulled revisions.'),
961
 
        custom_help('directory',
 
961
        Option('directory',
962
962
            help='Branch to pull into, '
963
 
                 'rather than the one containing the working directory.'),
 
963
                 'rather than the one containing the working directory.',
 
964
            short_name='d',
 
965
            type=unicode,
 
966
            ),
964
967
        Option('local',
965
968
            help="Perform a local pull in a bound "
966
969
                 "branch.  Local pulls are not applied to "
981
984
        try:
982
985
            tree_to = WorkingTree.open_containing(directory)[0]
983
986
            branch_to = tree_to.branch
984
 
            self.add_cleanup(tree_to.lock_write().unlock)
985
987
        except errors.NoWorkingTree:
986
988
            tree_to = None
987
989
            branch_to = Branch.open_containing(directory)[0]
988
 
            self.add_cleanup(branch_to.lock_write().unlock)
989
 
 
 
990
        
990
991
        if local and not branch_to.get_bound_location():
991
992
            raise errors.LocalRequiresBoundBranch()
992
993
 
1022
1023
        else:
1023
1024
            branch_from = Branch.open(location,
1024
1025
                possible_transports=possible_transports)
1025
 
            self.add_cleanup(branch_from.lock_read().unlock)
1026
1026
 
1027
1027
            if branch_to.get_parent() is None or remember:
1028
1028
                branch_to.set_parent(branch_from.base)
1029
1029
 
 
1030
        if branch_from is not branch_to:
 
1031
            branch_from.lock_read()
 
1032
            self.add_cleanup(branch_from.unlock)
1030
1033
        if revision is not None:
1031
1034
            revision_id = revision.as_revision_id(branch_from)
1032
1035
 
 
1036
        branch_to.lock_write()
 
1037
        self.add_cleanup(branch_to.unlock)
1033
1038
        if tree_to is not None:
1034
1039
            view_info = _get_view_info_for_change_reporter(tree_to)
1035
1040
            change_reporter = delta._ChangeReporter(
1050
1055
 
1051
1056
 
1052
1057
class cmd_push(Command):
1053
 
    __doc__ = """Update a mirror of this branch.
 
1058
    """Update a mirror of this branch.
1054
1059
 
1055
1060
    The target branch will not have its working tree populated because this
1056
1061
    is both expensive, and is not supported on remote file systems.
1080
1085
        Option('create-prefix',
1081
1086
               help='Create the path leading up to the branch '
1082
1087
                    'if it does not already exist.'),
1083
 
        custom_help('directory',
 
1088
        Option('directory',
1084
1089
            help='Branch to push from, '
1085
 
                 'rather than the one containing the working directory.'),
 
1090
                 'rather than the one containing the working directory.',
 
1091
            short_name='d',
 
1092
            type=unicode,
 
1093
            ),
1086
1094
        Option('use-existing-dir',
1087
1095
               help='By default push will fail if the target'
1088
1096
                    ' directory exists, but does not already'
1114
1122
        # Get the source branch
1115
1123
        (tree, br_from,
1116
1124
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1125
        if strict is None:
 
1126
            strict = br_from.get_config().get_user_option_as_bool('push_strict')
 
1127
        if strict is None: strict = True # default value
1117
1128
        # Get the tip's revision_id
1118
1129
        revision = _get_one_revision('push', revision)
1119
1130
        if revision is not None:
1120
1131
            revision_id = revision.in_history(br_from).rev_id
1121
1132
        else:
1122
1133
            revision_id = None
1123
 
        if tree is not None and revision_id is None:
1124
 
            tree.check_changed_or_out_of_date(
1125
 
                strict, 'push_strict',
1126
 
                more_error='Use --no-strict to force the push.',
1127
 
                more_warning='Uncommitted changes will not be pushed.')
 
1134
        if strict and tree is not None and revision_id is None:
 
1135
            if (tree.has_changes()):
 
1136
                raise errors.UncommittedChanges(
 
1137
                    tree, more='Use --no-strict to force the push.')
 
1138
            if tree.last_revision() != tree.branch.last_revision():
 
1139
                # The tree has lost sync with its branch, there is little
 
1140
                # chance that the user is aware of it but he can still force
 
1141
                # the push with --no-strict
 
1142
                raise errors.OutOfDateTree(
 
1143
                    tree, more='Use --no-strict to force the push.')
 
1144
 
1128
1145
        # Get the stacked_on branch, if any
1129
1146
        if stacked_on is not None:
1130
1147
            stacked_on = urlutils.normalize_url(stacked_on)
1162
1179
 
1163
1180
 
1164
1181
class cmd_branch(Command):
1165
 
    __doc__ = """Create a new branch that is a copy of an existing branch.
 
1182
    """Create a new branch that is a copy of an existing branch.
1166
1183
 
1167
1184
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1168
1185
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1208
1225
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1209
1226
            from_location)
1210
1227
        revision = _get_one_revision('branch', revision)
1211
 
        self.add_cleanup(br_from.lock_read().unlock)
 
1228
        br_from.lock_read()
 
1229
        self.add_cleanup(br_from.unlock)
1212
1230
        if revision is not None:
1213
1231
            revision_id = revision.as_revision_id(br_from)
1214
1232
        else:
1274
1292
 
1275
1293
 
1276
1294
class cmd_checkout(Command):
1277
 
    __doc__ = """Create a new checkout of an existing branch.
 
1295
    """Create a new checkout of an existing branch.
1278
1296
 
1279
1297
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1280
1298
    the branch found in '.'. This is useful if you have removed the working tree
1343
1361
 
1344
1362
 
1345
1363
class cmd_renames(Command):
1346
 
    __doc__ = """Show list of renamed files.
 
1364
    """Show list of renamed files.
1347
1365
    """
1348
1366
    # TODO: Option to show renames between two historical versions.
1349
1367
 
1354
1372
    @display_command
1355
1373
    def run(self, dir=u'.'):
1356
1374
        tree = WorkingTree.open_containing(dir)[0]
1357
 
        self.add_cleanup(tree.lock_read().unlock)
 
1375
        tree.lock_read()
 
1376
        self.add_cleanup(tree.unlock)
1358
1377
        new_inv = tree.inventory
1359
1378
        old_tree = tree.basis_tree()
1360
 
        self.add_cleanup(old_tree.lock_read().unlock)
 
1379
        old_tree.lock_read()
 
1380
        self.add_cleanup(old_tree.unlock)
1361
1381
        old_inv = old_tree.inventory
1362
1382
        renames = []
1363
1383
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1373
1393
 
1374
1394
 
1375
1395
class cmd_update(Command):
1376
 
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1396
    """Update a tree to have the latest code committed to its branch.
1377
1397
 
1378
1398
    This will perform a merge into the working tree, and may generate
1379
1399
    conflicts. If you have any local changes, you will still
1401
1421
        master = branch.get_master_branch(
1402
1422
            possible_transports=possible_transports)
1403
1423
        if master is not None:
 
1424
            tree.lock_write()
1404
1425
            branch_location = master.base
1405
 
            tree.lock_write()
1406
1426
        else:
 
1427
            tree.lock_tree_write()
1407
1428
            branch_location = tree.branch.base
1408
 
            tree.lock_tree_write()
1409
1429
        self.add_cleanup(tree.unlock)
1410
1430
        # get rid of the final '/' and be ready for display
1411
 
        branch_location = urlutils.unescape_for_display(
1412
 
            branch_location.rstrip('/'),
1413
 
            self.outf.encoding)
 
1431
        branch_location = urlutils.unescape_for_display(branch_location[:-1],
 
1432
                                                        self.outf.encoding)
1414
1433
        existing_pending_merges = tree.get_parent_ids()[1:]
1415
1434
        if master is None:
1416
1435
            old_tip = None
1424
1443
        else:
1425
1444
            revision_id = branch.last_revision()
1426
1445
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1427
 
            revno = branch.revision_id_to_dotted_revno(revision_id)
1428
 
            note("Tree is up to date at revision %s of branch %s" %
1429
 
                ('.'.join(map(str, revno)), branch_location))
 
1446
            revno = branch.revision_id_to_revno(revision_id)
 
1447
            note("Tree is up to date at revision %d of branch %s" %
 
1448
                (revno, branch_location))
1430
1449
            return 0
1431
1450
        view_info = _get_view_info_for_change_reporter(tree)
1432
1451
        change_reporter = delta._ChangeReporter(
1444
1463
                                  "bzr update --revision only works"
1445
1464
                                  " for a revision in the branch history"
1446
1465
                                  % (e.revision))
1447
 
        revno = tree.branch.revision_id_to_dotted_revno(
 
1466
        revno = tree.branch.revision_id_to_revno(
1448
1467
            _mod_revision.ensure_null(tree.last_revision()))
1449
 
        note('Updated to revision %s of branch %s' %
1450
 
             ('.'.join(map(str, revno)), branch_location))
1451
 
        parent_ids = tree.get_parent_ids()
1452
 
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
 
1468
        note('Updated to revision %d of branch %s' %
 
1469
             (revno, branch_location))
 
1470
        if tree.get_parent_ids()[1:] != existing_pending_merges:
1453
1471
            note('Your local commits will now show as pending merges with '
1454
1472
                 "'bzr status', and can be committed with 'bzr commit'.")
1455
1473
        if conflicts != 0:
1459
1477
 
1460
1478
 
1461
1479
class cmd_info(Command):
1462
 
    __doc__ = """Show information about a working tree, branch or repository.
 
1480
    """Show information about a working tree, branch or repository.
1463
1481
 
1464
1482
    This command will show all known locations and formats associated to the
1465
1483
    tree, branch or repository.
1503
1521
 
1504
1522
 
1505
1523
class cmd_remove(Command):
1506
 
    __doc__ = """Remove files or directories.
 
1524
    """Remove files or directories.
1507
1525
 
1508
1526
    This makes bzr stop tracking changes to the specified files. bzr will delete
1509
1527
    them if they can easily be recovered using revert. If no options or
1531
1549
        if file_list is not None:
1532
1550
            file_list = [f for f in file_list]
1533
1551
 
1534
 
        self.add_cleanup(tree.lock_write().unlock)
 
1552
        tree.lock_write()
 
1553
        self.add_cleanup(tree.unlock)
1535
1554
        # Heuristics should probably all move into tree.remove_smart or
1536
1555
        # some such?
1537
1556
        if new:
1556
1575
 
1557
1576
 
1558
1577
class cmd_file_id(Command):
1559
 
    __doc__ = """Print file_id of a particular file or directory.
 
1578
    """Print file_id of a particular file or directory.
1560
1579
 
1561
1580
    The file_id is assigned when the file is first added and remains the
1562
1581
    same through all revisions where the file exists, even when it is
1578
1597
 
1579
1598
 
1580
1599
class cmd_file_path(Command):
1581
 
    __doc__ = """Print path of file_ids to a file or directory.
 
1600
    """Print path of file_ids to a file or directory.
1582
1601
 
1583
1602
    This prints one line for each directory down to the target,
1584
1603
    starting at the branch root.
1600
1619
 
1601
1620
 
1602
1621
class cmd_reconcile(Command):
1603
 
    __doc__ = """Reconcile bzr metadata in a branch.
 
1622
    """Reconcile bzr metadata in a branch.
1604
1623
 
1605
1624
    This can correct data mismatches that may have been caused by
1606
1625
    previous ghost operations or bzr upgrades. You should only
1628
1647
 
1629
1648
 
1630
1649
class cmd_revision_history(Command):
1631
 
    __doc__ = """Display the list of revision ids on a branch."""
 
1650
    """Display the list of revision ids on a branch."""
1632
1651
 
1633
1652
    _see_also = ['log']
1634
1653
    takes_args = ['location?']
1644
1663
 
1645
1664
 
1646
1665
class cmd_ancestry(Command):
1647
 
    __doc__ = """List all revisions merged into this branch."""
 
1666
    """List all revisions merged into this branch."""
1648
1667
 
1649
1668
    _see_also = ['log', 'revision-history']
1650
1669
    takes_args = ['location?']
1669
1688
 
1670
1689
 
1671
1690
class cmd_init(Command):
1672
 
    __doc__ = """Make a directory into a versioned branch.
 
1691
    """Make a directory into a versioned branch.
1673
1692
 
1674
1693
    Use this to create an empty branch, or before importing an
1675
1694
    existing project.
1778
1797
 
1779
1798
 
1780
1799
class cmd_init_repository(Command):
1781
 
    __doc__ = """Create a shared repository for branches to share storage space.
 
1800
    """Create a shared repository for branches to share storage space.
1782
1801
 
1783
1802
    New branches created under the repository directory will store their
1784
1803
    revisions in the repository, not in the branch directory.  For branches
1838
1857
 
1839
1858
 
1840
1859
class cmd_diff(Command):
1841
 
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1860
    """Show differences in the working tree, between revisions or branches.
1842
1861
 
1843
1862
    If no arguments are given, all changes for the current tree are listed.
1844
1863
    If files are given, only the changes in those files are listed.
1930
1949
            help='Use this command to compare files.',
1931
1950
            type=unicode,
1932
1951
            ),
1933
 
        RegistryOption('format',
1934
 
            help='Diff format to use.',
1935
 
            lazy_registry=('bzrlib.diff', 'format_registry'),
1936
 
            value_switches=False, title='Diff format'),
1937
1952
        ]
1938
1953
    aliases = ['di', 'dif']
1939
1954
    encoding_type = 'exact'
1940
1955
 
1941
1956
    @display_command
1942
1957
    def run(self, revision=None, file_list=None, diff_options=None,
1943
 
            prefix=None, old=None, new=None, using=None, format=None):
1944
 
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
1945
 
            show_diff_trees)
 
1958
            prefix=None, old=None, new=None, using=None):
 
1959
        from bzrlib.diff import get_trees_and_branches_to_diff, show_diff_trees
1946
1960
 
1947
1961
        if (prefix is None) or (prefix == '0'):
1948
1962
            # diff -p0 format
1962
1976
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1963
1977
                                         ' one or two revision specifiers')
1964
1978
 
1965
 
        if using is not None and format is not None:
1966
 
            raise errors.BzrCommandError('--using and --format are mutually '
1967
 
                'exclusive.')
1968
 
 
1969
1979
        (old_tree, new_tree,
1970
1980
         old_branch, new_branch,
1971
 
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
1972
 
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
1973
 
        # GNU diff on Windows uses ANSI encoding for filenames
1974
 
        path_encoding = osutils.get_diff_header_encoding()
 
1981
         specific_files, extra_trees) = get_trees_and_branches_to_diff(
 
1982
            file_list, revision, old, new, apply_view=True)
1975
1983
        return show_diff_trees(old_tree, new_tree, sys.stdout,
1976
1984
                               specific_files=specific_files,
1977
1985
                               external_diff_options=diff_options,
1978
1986
                               old_label=old_label, new_label=new_label,
1979
 
                               extra_trees=extra_trees,
1980
 
                               path_encoding=path_encoding,
1981
 
                               using=using,
1982
 
                               format_cls=format)
 
1987
                               extra_trees=extra_trees, using=using)
1983
1988
 
1984
1989
 
1985
1990
class cmd_deleted(Command):
1986
 
    __doc__ = """List files deleted in the working tree.
 
1991
    """List files deleted in the working tree.
1987
1992
    """
1988
1993
    # TODO: Show files deleted since a previous revision, or
1989
1994
    # between two revisions.
1992
1997
    # level of effort but possibly much less IO.  (Or possibly not,
1993
1998
    # if the directories are very large...)
1994
1999
    _see_also = ['status', 'ls']
1995
 
    takes_options = ['directory', 'show-ids']
 
2000
    takes_options = ['show-ids']
1996
2001
 
1997
2002
    @display_command
1998
 
    def run(self, show_ids=False, directory=u'.'):
1999
 
        tree = WorkingTree.open_containing(directory)[0]
2000
 
        self.add_cleanup(tree.lock_read().unlock)
 
2003
    def run(self, show_ids=False):
 
2004
        tree = WorkingTree.open_containing(u'.')[0]
 
2005
        tree.lock_read()
 
2006
        self.add_cleanup(tree.unlock)
2001
2007
        old = tree.basis_tree()
2002
 
        self.add_cleanup(old.lock_read().unlock)
 
2008
        old.lock_read()
 
2009
        self.add_cleanup(old.unlock)
2003
2010
        for path, ie in old.inventory.iter_entries():
2004
2011
            if not tree.has_id(ie.file_id):
2005
2012
                self.outf.write(path)
2010
2017
 
2011
2018
 
2012
2019
class cmd_modified(Command):
2013
 
    __doc__ = """List files modified in working tree.
 
2020
    """List files modified in working tree.
2014
2021
    """
2015
2022
 
2016
2023
    hidden = True
2017
2024
    _see_also = ['status', 'ls']
2018
 
    takes_options = ['directory', 'null']
 
2025
    takes_options = [
 
2026
            Option('null',
 
2027
                   help='Write an ascii NUL (\\0) separator '
 
2028
                   'between files rather than a newline.')
 
2029
            ]
2019
2030
 
2020
2031
    @display_command
2021
 
    def run(self, null=False, directory=u'.'):
2022
 
        tree = WorkingTree.open_containing(directory)[0]
 
2032
    def run(self, null=False):
 
2033
        tree = WorkingTree.open_containing(u'.')[0]
2023
2034
        td = tree.changes_from(tree.basis_tree())
2024
2035
        for path, id, kind, text_modified, meta_modified in td.modified:
2025
2036
            if null:
2029
2040
 
2030
2041
 
2031
2042
class cmd_added(Command):
2032
 
    __doc__ = """List files added in working tree.
 
2043
    """List files added in working tree.
2033
2044
    """
2034
2045
 
2035
2046
    hidden = True
2036
2047
    _see_also = ['status', 'ls']
2037
 
    takes_options = ['directory', 'null']
 
2048
    takes_options = [
 
2049
            Option('null',
 
2050
                   help='Write an ascii NUL (\\0) separator '
 
2051
                   'between files rather than a newline.')
 
2052
            ]
2038
2053
 
2039
2054
    @display_command
2040
 
    def run(self, null=False, directory=u'.'):
2041
 
        wt = WorkingTree.open_containing(directory)[0]
2042
 
        self.add_cleanup(wt.lock_read().unlock)
 
2055
    def run(self, null=False):
 
2056
        wt = WorkingTree.open_containing(u'.')[0]
 
2057
        wt.lock_read()
 
2058
        self.add_cleanup(wt.unlock)
2043
2059
        basis = wt.basis_tree()
2044
 
        self.add_cleanup(basis.lock_read().unlock)
 
2060
        basis.lock_read()
 
2061
        self.add_cleanup(basis.unlock)
2045
2062
        basis_inv = basis.inventory
2046
2063
        inv = wt.inventory
2047
2064
        for file_id in inv:
2050
2067
            if inv.is_root(file_id) and len(basis_inv) == 0:
2051
2068
                continue
2052
2069
            path = inv.id2path(file_id)
2053
 
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
 
2070
            if not os.access(osutils.abspath(path), os.F_OK):
2054
2071
                continue
2055
2072
            if null:
2056
2073
                self.outf.write(path + '\0')
2059
2076
 
2060
2077
 
2061
2078
class cmd_root(Command):
2062
 
    __doc__ = """Show the tree root directory.
 
2079
    """Show the tree root directory.
2063
2080
 
2064
2081
    The root is the nearest enclosing directory with a .bzr control
2065
2082
    directory."""
2089
2106
 
2090
2107
 
2091
2108
class cmd_log(Command):
2092
 
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2109
    """Show historical log for a branch or subset of a branch.
2093
2110
 
2094
2111
    log is bzr's default tool for exploring the history of a branch.
2095
2112
    The branch to use is taken from the first parameter. If no parameters
2256
2273
                   help='Show just the specified revision.'
2257
2274
                   ' See also "help revisionspec".'),
2258
2275
            'log-format',
2259
 
            RegistryOption('authors',
2260
 
                'What names to list as authors - first, all or committer.',
2261
 
                title='Authors',
2262
 
                lazy_registry=('bzrlib.log', 'author_list_registry'),
2263
 
            ),
2264
2276
            Option('levels',
2265
2277
                   short_name='n',
2266
2278
                   help='Number of levels to display - 0 for all, 1 for flat.',
2281
2293
                   help='Show changes made in each revision as a patch.'),
2282
2294
            Option('include-merges',
2283
2295
                   help='Show merged revisions like --levels 0 does.'),
2284
 
            Option('exclude-common-ancestry',
2285
 
                   help='Display only the revisions that are not part'
2286
 
                   ' of both ancestries (require -rX..Y)'
2287
 
                   )
2288
2296
            ]
2289
2297
    encoding_type = 'replace'
2290
2298
 
2300
2308
            message=None,
2301
2309
            limit=None,
2302
2310
            show_diff=False,
2303
 
            include_merges=False,
2304
 
            authors=None,
2305
 
            exclude_common_ancestry=False,
2306
 
            ):
 
2311
            include_merges=False):
2307
2312
        from bzrlib.log import (
2308
2313
            Logger,
2309
2314
            make_log_request_dict,
2310
2315
            _get_info_for_log_files,
2311
2316
            )
2312
2317
        direction = (forward and 'forward') or 'reverse'
2313
 
        if (exclude_common_ancestry
2314
 
            and (revision is None or len(revision) != 2)):
2315
 
            raise errors.BzrCommandError(
2316
 
                '--exclude-common-ancestry requires -r with two revisions')
2317
2318
        if include_merges:
2318
2319
            if levels is None:
2319
2320
                levels = 0
2335
2336
        if file_list:
2336
2337
            # find the file ids to log and check for directory filtering
2337
2338
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2338
 
                revision, file_list, self.add_cleanup)
 
2339
                revision, file_list)
 
2340
            self.add_cleanup(b.unlock)
2339
2341
            for relpath, file_id, kind in file_info_list:
2340
2342
                if file_id is None:
2341
2343
                    raise errors.BzrCommandError(
2359
2361
                location = '.'
2360
2362
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2361
2363
            b = dir.open_branch()
2362
 
            self.add_cleanup(b.lock_read().unlock)
 
2364
            b.lock_read()
 
2365
            self.add_cleanup(b.unlock)
2363
2366
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2364
2367
 
2365
2368
        # Decide on the type of delta & diff filtering to use
2385
2388
                        show_timezone=timezone,
2386
2389
                        delta_format=get_verbosity_level(),
2387
2390
                        levels=levels,
2388
 
                        show_advice=levels is None,
2389
 
                        author_list_handler=authors)
 
2391
                        show_advice=levels is None)
2390
2392
 
2391
2393
        # Choose the algorithm for doing the logging. It's annoying
2392
2394
        # having multiple code paths like this but necessary until
2411
2413
            direction=direction, specific_fileids=file_ids,
2412
2414
            start_revision=rev1, end_revision=rev2, limit=limit,
2413
2415
            message_search=message, delta_type=delta_type,
2414
 
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2415
 
            exclude_common_ancestry=exclude_common_ancestry,
2416
 
            )
 
2416
            diff_type=diff_type, _match_using_deltas=match_using_deltas)
2417
2417
        Logger(b, rqst).show(lf)
2418
2418
 
2419
2419
 
2477
2477
 
2478
2478
 
2479
2479
class cmd_touching_revisions(Command):
2480
 
    __doc__ = """Return revision-ids which affected a particular file.
 
2480
    """Return revision-ids which affected a particular file.
2481
2481
 
2482
2482
    A more user-friendly interface is "bzr log FILE".
2483
2483
    """
2490
2490
        tree, relpath = WorkingTree.open_containing(filename)
2491
2491
        file_id = tree.path2id(relpath)
2492
2492
        b = tree.branch
2493
 
        self.add_cleanup(b.lock_read().unlock)
 
2493
        b.lock_read()
 
2494
        self.add_cleanup(b.unlock)
2494
2495
        touching_revs = log.find_touching_revisions(b, file_id)
2495
2496
        for revno, revision_id, what in touching_revs:
2496
2497
            self.outf.write("%6d %s\n" % (revno, what))
2497
2498
 
2498
2499
 
2499
2500
class cmd_ls(Command):
2500
 
    __doc__ = """List files in a tree.
 
2501
    """List files in a tree.
2501
2502
    """
2502
2503
 
2503
2504
    _see_also = ['status', 'cat']
2509
2510
                   help='Recurse into subdirectories.'),
2510
2511
            Option('from-root',
2511
2512
                   help='Print paths relative to the root of the branch.'),
2512
 
            Option('unknown', short_name='u',
2513
 
                help='Print unknown files.'),
 
2513
            Option('unknown', help='Print unknown files.'),
2514
2514
            Option('versioned', help='Print versioned files.',
2515
2515
                   short_name='V'),
2516
 
            Option('ignored', short_name='i',
2517
 
                help='Print ignored files.'),
2518
 
            Option('kind', short_name='k',
 
2516
            Option('ignored', help='Print ignored files.'),
 
2517
            Option('null',
 
2518
                   help='Write an ascii NUL (\\0) separator '
 
2519
                   'between files rather than a newline.'),
 
2520
            Option('kind',
2519
2521
                   help='List entries of a particular kind: file, directory, symlink.',
2520
2522
                   type=unicode),
2521
 
            'null',
2522
2523
            'show-ids',
2523
 
            'directory',
2524
2524
            ]
2525
2525
    @display_command
2526
2526
    def run(self, revision=None, verbose=False,
2527
2527
            recursive=False, from_root=False,
2528
2528
            unknown=False, versioned=False, ignored=False,
2529
 
            null=False, kind=None, show_ids=False, path=None, directory=None):
 
2529
            null=False, kind=None, show_ids=False, path=None):
2530
2530
 
2531
2531
        if kind and kind not in ('file', 'directory', 'symlink'):
2532
2532
            raise errors.BzrCommandError('invalid kind specified')
2544
2544
                raise errors.BzrCommandError('cannot specify both --from-root'
2545
2545
                                             ' and PATH')
2546
2546
            fs_path = path
2547
 
        tree, branch, relpath = \
2548
 
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2547
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2548
            fs_path)
2549
2549
 
2550
2550
        # Calculate the prefix to use
2551
2551
        prefix = None
2566
2566
                view_str = views.view_display_str(view_files)
2567
2567
                note("Ignoring files outside view. View is %s" % view_str)
2568
2568
 
2569
 
        self.add_cleanup(tree.lock_read().unlock)
 
2569
        tree.lock_read()
 
2570
        self.add_cleanup(tree.unlock)
2570
2571
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2571
2572
            from_dir=relpath, recursive=recursive):
2572
2573
            # Apply additional masking
2614
2615
 
2615
2616
 
2616
2617
class cmd_unknowns(Command):
2617
 
    __doc__ = """List unknown files.
 
2618
    """List unknown files.
2618
2619
    """
2619
2620
 
2620
2621
    hidden = True
2621
2622
    _see_also = ['ls']
2622
 
    takes_options = ['directory']
2623
2623
 
2624
2624
    @display_command
2625
 
    def run(self, directory=u'.'):
2626
 
        for f in WorkingTree.open_containing(directory)[0].unknowns():
 
2625
    def run(self):
 
2626
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
2627
2627
            self.outf.write(osutils.quotefn(f) + '\n')
2628
2628
 
2629
2629
 
2630
2630
class cmd_ignore(Command):
2631
 
    __doc__ = """Ignore specified files or patterns.
 
2631
    """Ignore specified files or patterns.
2632
2632
 
2633
2633
    See ``bzr help patterns`` for details on the syntax of patterns.
2634
2634
 
2643
2643
    using this command or directly by using an editor, be sure to commit
2644
2644
    it.
2645
2645
    
2646
 
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2647
 
    the global ignore file can be found in the application data directory as
2648
 
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2649
 
    Global ignores are not touched by this command. The global ignore file
2650
 
    can be edited directly using an editor.
2651
 
 
2652
2646
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2653
2647
    precedence over regular ignores.  Such exceptions are used to specify
2654
2648
    files that should be versioned which would otherwise be ignored.
2694
2688
 
2695
2689
    _see_also = ['status', 'ignored', 'patterns']
2696
2690
    takes_args = ['name_pattern*']
2697
 
    takes_options = ['directory',
2698
 
        Option('default-rules',
2699
 
               help='Display the default ignore rules that bzr uses.')
 
2691
    takes_options = [
 
2692
        Option('old-default-rules',
 
2693
               help='Write out the ignore rules bzr < 0.9 always used.')
2700
2694
        ]
2701
2695
 
2702
 
    def run(self, name_pattern_list=None, default_rules=None,
2703
 
            directory=u'.'):
 
2696
    def run(self, name_pattern_list=None, old_default_rules=None):
2704
2697
        from bzrlib import ignores
2705
 
        if default_rules is not None:
2706
 
            # dump the default rules and exit
2707
 
            for pattern in ignores.USER_DEFAULTS:
 
2698
        if old_default_rules is not None:
 
2699
            # dump the rules and exit
 
2700
            for pattern in ignores.OLD_DEFAULTS:
2708
2701
                self.outf.write("%s\n" % pattern)
2709
2702
            return
2710
2703
        if not name_pattern_list:
2711
2704
            raise errors.BzrCommandError("ignore requires at least one "
2712
 
                "NAME_PATTERN or --default-rules.")
 
2705
                                  "NAME_PATTERN or --old-default-rules")
2713
2706
        name_pattern_list = [globbing.normalize_pattern(p)
2714
2707
                             for p in name_pattern_list]
2715
 
        bad_patterns = ''
2716
 
        for p in name_pattern_list:
2717
 
            if not globbing.Globster.is_pattern_valid(p):
2718
 
                bad_patterns += ('\n  %s' % p)
2719
 
        if bad_patterns:
2720
 
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2721
 
            ui.ui_factory.show_error(msg)
2722
 
            raise errors.InvalidPattern('')
2723
2708
        for name_pattern in name_pattern_list:
2724
2709
            if (name_pattern[0] == '/' or
2725
2710
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2726
2711
                raise errors.BzrCommandError(
2727
2712
                    "NAME_PATTERN should not be an absolute path")
2728
 
        tree, relpath = WorkingTree.open_containing(directory)
 
2713
        tree, relpath = WorkingTree.open_containing(u'.')
2729
2714
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2730
2715
        ignored = globbing.Globster(name_pattern_list)
2731
2716
        matches = []
2732
 
        self.add_cleanup(tree.lock_read().unlock)
 
2717
        tree.lock_read()
2733
2718
        for entry in tree.list_files():
2734
2719
            id = entry[3]
2735
2720
            if id is not None:
2736
2721
                filename = entry[0]
2737
2722
                if ignored.match(filename):
2738
2723
                    matches.append(filename)
 
2724
        tree.unlock()
2739
2725
        if len(matches) > 0:
2740
2726
            self.outf.write("Warning: the following files are version controlled and"
2741
2727
                  " match your ignore pattern:\n%s"
2744
2730
 
2745
2731
 
2746
2732
class cmd_ignored(Command):
2747
 
    __doc__ = """List ignored files and the patterns that matched them.
 
2733
    """List ignored files and the patterns that matched them.
2748
2734
 
2749
2735
    List all the ignored files and the ignore pattern that caused the file to
2750
2736
    be ignored.
2756
2742
 
2757
2743
    encoding_type = 'replace'
2758
2744
    _see_also = ['ignore', 'ls']
2759
 
    takes_options = ['directory']
2760
2745
 
2761
2746
    @display_command
2762
 
    def run(self, directory=u'.'):
2763
 
        tree = WorkingTree.open_containing(directory)[0]
2764
 
        self.add_cleanup(tree.lock_read().unlock)
 
2747
    def run(self):
 
2748
        tree = WorkingTree.open_containing(u'.')[0]
 
2749
        tree.lock_read()
 
2750
        self.add_cleanup(tree.unlock)
2765
2751
        for path, file_class, kind, file_id, entry in tree.list_files():
2766
2752
            if file_class != 'I':
2767
2753
                continue
2771
2757
 
2772
2758
 
2773
2759
class cmd_lookup_revision(Command):
2774
 
    __doc__ = """Lookup the revision-id from a revision-number
 
2760
    """Lookup the revision-id from a revision-number
2775
2761
 
2776
2762
    :Examples:
2777
2763
        bzr lookup-revision 33
2778
2764
    """
2779
2765
    hidden = True
2780
2766
    takes_args = ['revno']
2781
 
    takes_options = ['directory']
2782
2767
 
2783
2768
    @display_command
2784
 
    def run(self, revno, directory=u'.'):
 
2769
    def run(self, revno):
2785
2770
        try:
2786
2771
            revno = int(revno)
2787
2772
        except ValueError:
2788
2773
            raise errors.BzrCommandError("not a valid revision-number: %r"
2789
2774
                                         % revno)
2790
 
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
 
2775
        revid = WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2791
2776
        self.outf.write("%s\n" % revid)
2792
2777
 
2793
2778
 
2794
2779
class cmd_export(Command):
2795
 
    __doc__ = """Export current or past revision to a destination directory or archive.
 
2780
    """Export current or past revision to a destination directory or archive.
2796
2781
 
2797
2782
    If no revision is specified this exports the last committed revision.
2798
2783
 
2820
2805
      =================       =========================
2821
2806
    """
2822
2807
    takes_args = ['dest', 'branch_or_subdir?']
2823
 
    takes_options = ['directory',
 
2808
    takes_options = [
2824
2809
        Option('format',
2825
2810
               help="Type of file to export to.",
2826
2811
               type=unicode),
2835
2820
                    'revision in which it was changed.'),
2836
2821
        ]
2837
2822
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2838
 
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
 
2823
        root=None, filters=False, per_file_timestamps=False):
2839
2824
        from bzrlib.export import export
2840
2825
 
2841
2826
        if branch_or_subdir is None:
2842
 
            tree = WorkingTree.open_containing(directory)[0]
 
2827
            tree = WorkingTree.open_containing(u'.')[0]
2843
2828
            b = tree.branch
2844
2829
            subdir = None
2845
2830
        else:
2855
2840
 
2856
2841
 
2857
2842
class cmd_cat(Command):
2858
 
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
2843
    """Write the contents of a file as of a given revision to standard output.
2859
2844
 
2860
2845
    If no revision is nominated, the last revision is used.
2861
2846
 
2864
2849
    """
2865
2850
 
2866
2851
    _see_also = ['ls']
2867
 
    takes_options = ['directory',
 
2852
    takes_options = [
2868
2853
        Option('name-from-revision', help='The path name in the old tree.'),
2869
2854
        Option('filters', help='Apply content filters to display the '
2870
2855
                'convenience form.'),
2875
2860
 
2876
2861
    @display_command
2877
2862
    def run(self, filename, revision=None, name_from_revision=False,
2878
 
            filters=False, directory=None):
 
2863
            filters=False):
2879
2864
        if revision is not None and len(revision) != 1:
2880
2865
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2881
2866
                                         " one revision specifier")
2882
2867
        tree, branch, relpath = \
2883
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
2884
 
        self.add_cleanup(branch.lock_read().unlock)
 
2868
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2869
        branch.lock_read()
 
2870
        self.add_cleanup(branch.unlock)
2885
2871
        return self._run(tree, branch, relpath, filename, revision,
2886
2872
                         name_from_revision, filters)
2887
2873
 
2890
2876
        if tree is None:
2891
2877
            tree = b.basis_tree()
2892
2878
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2893
 
        self.add_cleanup(rev_tree.lock_read().unlock)
 
2879
        rev_tree.lock_read()
 
2880
        self.add_cleanup(rev_tree.unlock)
2894
2881
 
2895
2882
        old_file_id = rev_tree.path2id(relpath)
2896
2883
 
2939
2926
 
2940
2927
 
2941
2928
class cmd_local_time_offset(Command):
2942
 
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
2929
    """Show the offset in seconds from GMT to local time."""
2943
2930
    hidden = True
2944
2931
    @display_command
2945
2932
    def run(self):
2948
2935
 
2949
2936
 
2950
2937
class cmd_commit(Command):
2951
 
    __doc__ = """Commit changes into a new revision.
 
2938
    """Commit changes into a new revision.
2952
2939
 
2953
2940
    An explanatory message needs to be given for each commit. This is
2954
2941
    often done by using the --message option (getting the message from the
3062
3049
                         "the master branch until a normal commit "
3063
3050
                         "is performed."
3064
3051
                    ),
3065
 
             Option('show-diff', short_name='p',
 
3052
             Option('show-diff',
3066
3053
                    help='When no message is supplied, show the diff along'
3067
3054
                    ' with the status summary in the message editor.'),
3068
3055
             ]
3148
3135
                    '(use --file "%(f)s" to take commit message from that file)'
3149
3136
                    % { 'f': message })
3150
3137
                ui.ui_factory.show_warning(warning_msg)
3151
 
            if '\r' in message:
3152
 
                message = message.replace('\r\n', '\n')
3153
 
                message = message.replace('\r', '\n')
3154
 
            if file:
3155
 
                raise errors.BzrCommandError(
3156
 
                    "please specify either --message or --file")
3157
3138
 
3158
3139
        def get_message(commit_obj):
3159
3140
            """Callback to get commit message"""
3160
 
            if file:
3161
 
                f = codecs.open(file, 'rt', osutils.get_user_encoding())
3162
 
                try:
3163
 
                    my_message = f.read()
3164
 
                finally:
3165
 
                    f.close()
3166
 
            elif message is not None:
3167
 
                my_message = message
3168
 
            else:
3169
 
                # No message supplied: make one up.
3170
 
                # text is the status of the tree
3171
 
                text = make_commit_message_template_encoded(tree,
 
3141
            my_message = message
 
3142
            if my_message is not None and '\r' in my_message:
 
3143
                my_message = my_message.replace('\r\n', '\n')
 
3144
                my_message = my_message.replace('\r', '\n')
 
3145
            if my_message is None and not file:
 
3146
                t = make_commit_message_template_encoded(tree,
3172
3147
                        selected_list, diff=show_diff,
3173
3148
                        output_encoding=osutils.get_user_encoding())
3174
 
                # start_message is the template generated from hooks
3175
 
                # XXX: Warning - looks like hooks return unicode,
3176
 
                # make_commit_message_template_encoded returns user encoding.
3177
 
                # We probably want to be using edit_commit_message instead to
3178
 
                # avoid this.
3179
3149
                start_message = generate_commit_message_template(commit_obj)
3180
 
                my_message = edit_commit_message_encoded(text,
 
3150
                my_message = edit_commit_message_encoded(t,
3181
3151
                    start_message=start_message)
3182
3152
                if my_message is None:
3183
3153
                    raise errors.BzrCommandError("please specify a commit"
3184
3154
                        " message with either --message or --file")
 
3155
            elif my_message and file:
 
3156
                raise errors.BzrCommandError(
 
3157
                    "please specify either --message or --file")
 
3158
            if file:
 
3159
                my_message = codecs.open(file, 'rt',
 
3160
                                         osutils.get_user_encoding()).read()
3185
3161
            if my_message == "":
3186
3162
                raise errors.BzrCommandError("empty commit message specified")
3187
3163
            return my_message
3199
3175
                        timezone=offset,
3200
3176
                        exclude=safe_relpath_files(tree, exclude))
3201
3177
        except PointlessCommit:
 
3178
            # FIXME: This should really happen before the file is read in;
 
3179
            # perhaps prepare the commit; get the message; then actually commit
3202
3180
            raise errors.BzrCommandError("No changes to commit."
3203
3181
                              " Use --unchanged to commit anyhow.")
3204
3182
        except ConflictsInTree:
3217
3195
 
3218
3196
 
3219
3197
class cmd_check(Command):
3220
 
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3198
    """Validate working tree structure, branch consistency and repository history.
3221
3199
 
3222
3200
    This command checks various invariants about branch and repository storage
3223
3201
    to detect data corruption or bzr bugs.
3287
3265
 
3288
3266
 
3289
3267
class cmd_upgrade(Command):
3290
 
    __doc__ = """Upgrade branch storage to current format.
 
3268
    """Upgrade branch storage to current format.
3291
3269
 
3292
3270
    The check command or bzr developers may sometimes advise you to run
3293
3271
    this command. When the default format has changed you may also be warned
3311
3289
 
3312
3290
 
3313
3291
class cmd_whoami(Command):
3314
 
    __doc__ = """Show or set bzr user id.
 
3292
    """Show or set bzr user id.
3315
3293
 
3316
3294
    :Examples:
3317
3295
        Show the email of the current user::
3322
3300
 
3323
3301
            bzr whoami "Frank Chu <fchu@example.com>"
3324
3302
    """
3325
 
    takes_options = [ 'directory',
3326
 
                      Option('email',
 
3303
    takes_options = [ Option('email',
3327
3304
                             help='Display email address only.'),
3328
3305
                      Option('branch',
3329
3306
                             help='Set identity for the current branch instead of '
3333
3310
    encoding_type = 'replace'
3334
3311
 
3335
3312
    @display_command
3336
 
    def run(self, email=False, branch=False, name=None, directory=None):
 
3313
    def run(self, email=False, branch=False, name=None):
3337
3314
        if name is None:
3338
 
            if directory is None:
3339
 
                # use branch if we're inside one; otherwise global config
3340
 
                try:
3341
 
                    c = Branch.open_containing(u'.')[0].get_config()
3342
 
                except errors.NotBranchError:
3343
 
                    c = config.GlobalConfig()
3344
 
            else:
3345
 
                c = Branch.open(directory).get_config()
 
3315
            # use branch if we're inside one; otherwise global config
 
3316
            try:
 
3317
                c = Branch.open_containing('.')[0].get_config()
 
3318
            except errors.NotBranchError:
 
3319
                c = config.GlobalConfig()
3346
3320
            if email:
3347
3321
                self.outf.write(c.user_email() + '\n')
3348
3322
            else:
3358
3332
 
3359
3333
        # use global config unless --branch given
3360
3334
        if branch:
3361
 
            if directory is None:
3362
 
                c = Branch.open_containing(u'.')[0].get_config()
3363
 
            else:
3364
 
                c = Branch.open(directory).get_config()
 
3335
            c = Branch.open_containing('.')[0].get_config()
3365
3336
        else:
3366
3337
            c = config.GlobalConfig()
3367
3338
        c.set_user_option('email', name)
3368
3339
 
3369
3340
 
3370
3341
class cmd_nick(Command):
3371
 
    __doc__ = """Print or set the branch nickname.
 
3342
    """Print or set the branch nickname.
3372
3343
 
3373
3344
    If unset, the tree root directory name is used as the nickname.
3374
3345
    To print the current nickname, execute with no argument.
3379
3350
 
3380
3351
    _see_also = ['info']
3381
3352
    takes_args = ['nickname?']
3382
 
    takes_options = ['directory']
3383
 
    def run(self, nickname=None, directory=u'.'):
3384
 
        branch = Branch.open_containing(directory)[0]
 
3353
    def run(self, nickname=None):
 
3354
        branch = Branch.open_containing(u'.')[0]
3385
3355
        if nickname is None:
3386
3356
            self.printme(branch)
3387
3357
        else:
3393
3363
 
3394
3364
 
3395
3365
class cmd_alias(Command):
3396
 
    __doc__ = """Set/unset and display aliases.
 
3366
    """Set/unset and display aliases.
3397
3367
 
3398
3368
    :Examples:
3399
3369
        Show the current aliases::
3463
3433
 
3464
3434
 
3465
3435
class cmd_selftest(Command):
3466
 
    __doc__ = """Run internal test suite.
 
3436
    """Run internal test suite.
3467
3437
 
3468
3438
    If arguments are given, they are regular expressions that say which tests
3469
3439
    should run.  Tests matching any expression are run, and other tests are
3537
3507
                                 'throughout the test suite.',
3538
3508
                            type=get_transport_type),
3539
3509
                     Option('benchmark',
3540
 
                            help='Run the benchmarks rather than selftests.',
3541
 
                            hidden=True),
 
3510
                            help='Run the benchmarks rather than selftests.'),
3542
3511
                     Option('lsprof-timed',
3543
3512
                            help='Generate lsprof output for benchmarked'
3544
3513
                                 ' sections of code.'),
3545
3514
                     Option('lsprof-tests',
3546
3515
                            help='Generate lsprof output for each test.'),
 
3516
                     Option('cache-dir', type=str,
 
3517
                            help='Cache intermediate benchmark output in this '
 
3518
                                 'directory.'),
3547
3519
                     Option('first',
3548
3520
                            help='Run all tests, but run specified tests first.',
3549
3521
                            short_name='f',
3583
3555
 
3584
3556
    def run(self, testspecs_list=None, verbose=False, one=False,
3585
3557
            transport=None, benchmark=None,
3586
 
            lsprof_timed=None,
 
3558
            lsprof_timed=None, cache_dir=None,
3587
3559
            first=False, list_only=False,
3588
3560
            randomize=None, exclude=None, strict=False,
3589
3561
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3590
3562
            parallel=None, lsprof_tests=False):
3591
3563
        from bzrlib.tests import selftest
 
3564
        import bzrlib.benchmarks as benchmarks
 
3565
        from bzrlib.benchmarks import tree_creator
3592
3566
 
3593
3567
        # Make deprecation warnings visible, unless -Werror is set
3594
3568
        symbol_versioning.activate_deprecation_warnings(override=False)
3595
3569
 
 
3570
        if cache_dir is not None:
 
3571
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3596
3572
        if testspecs_list is not None:
3597
3573
            pattern = '|'.join(testspecs_list)
3598
3574
        else:
3604
3580
                raise errors.BzrCommandError("subunit not available. subunit "
3605
3581
                    "needs to be installed to use --subunit.")
3606
3582
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3607
 
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3608
 
            # stdout, which would corrupt the subunit stream. 
3609
 
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3610
 
            # following code can be deleted when it's sufficiently deployed
3611
 
            # -- vila/mgz 20100514
3612
 
            if (sys.platform == "win32"
3613
 
                and getattr(sys.stdout, 'fileno', None) is not None):
3614
 
                import msvcrt
3615
 
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3616
3583
        if parallel:
3617
3584
            self.additional_selftest_args.setdefault(
3618
3585
                'suite_decorators', []).append(parallel)
3619
3586
        if benchmark:
3620
 
            raise errors.BzrCommandError(
3621
 
                "--benchmark is no longer supported from bzr 2.2; "
3622
 
                "use bzr-usertest instead")
3623
 
        test_suite_factory = None
 
3587
            test_suite_factory = benchmarks.test_suite
 
3588
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
3589
            verbose = not is_quiet()
 
3590
            # TODO: should possibly lock the history file...
 
3591
            benchfile = open(".perf_history", "at", buffering=1)
 
3592
            self.add_cleanup(benchfile.close)
 
3593
        else:
 
3594
            test_suite_factory = None
 
3595
            benchfile = None
3624
3596
        selftest_kwargs = {"verbose": verbose,
3625
3597
                          "pattern": pattern,
3626
3598
                          "stop_on_failure": one,
3628
3600
                          "test_suite_factory": test_suite_factory,
3629
3601
                          "lsprof_timed": lsprof_timed,
3630
3602
                          "lsprof_tests": lsprof_tests,
 
3603
                          "bench_history": benchfile,
3631
3604
                          "matching_tests_first": first,
3632
3605
                          "list_only": list_only,
3633
3606
                          "random_seed": randomize,
3643
3616
 
3644
3617
 
3645
3618
class cmd_version(Command):
3646
 
    __doc__ = """Show version of bzr."""
 
3619
    """Show version of bzr."""
3647
3620
 
3648
3621
    encoding_type = 'replace'
3649
3622
    takes_options = [
3660
3633
 
3661
3634
 
3662
3635
class cmd_rocks(Command):
3663
 
    __doc__ = """Statement of optimism."""
 
3636
    """Statement of optimism."""
3664
3637
 
3665
3638
    hidden = True
3666
3639
 
3670
3643
 
3671
3644
 
3672
3645
class cmd_find_merge_base(Command):
3673
 
    __doc__ = """Find and print a base revision for merging two branches."""
 
3646
    """Find and print a base revision for merging two branches."""
3674
3647
    # TODO: Options to specify revisions on either side, as if
3675
3648
    #       merging only part of the history.
3676
3649
    takes_args = ['branch', 'other']
3682
3655
 
3683
3656
        branch1 = Branch.open_containing(branch)[0]
3684
3657
        branch2 = Branch.open_containing(other)[0]
3685
 
        self.add_cleanup(branch1.lock_read().unlock)
3686
 
        self.add_cleanup(branch2.lock_read().unlock)
 
3658
        branch1.lock_read()
 
3659
        self.add_cleanup(branch1.unlock)
 
3660
        branch2.lock_read()
 
3661
        self.add_cleanup(branch2.unlock)
3687
3662
        last1 = ensure_null(branch1.last_revision())
3688
3663
        last2 = ensure_null(branch2.last_revision())
3689
3664
 
3694
3669
 
3695
3670
 
3696
3671
class cmd_merge(Command):
3697
 
    __doc__ = """Perform a three-way merge.
 
3672
    """Perform a three-way merge.
3698
3673
 
3699
3674
    The source of the merge can be specified either in the form of a branch,
3700
3675
    or in the form of a path to a file containing a merge directive generated
3783
3758
                ' completely merged into the source, pull from the'
3784
3759
                ' source rather than merging.  When this happens,'
3785
3760
                ' you do not need to commit the result.'),
3786
 
        custom_help('directory',
 
3761
        Option('directory',
3787
3762
               help='Branch to merge into, '
3788
 
                    'rather than the one containing the working directory.'),
 
3763
                    'rather than the one containing the working directory.',
 
3764
               short_name='d',
 
3765
               type=unicode,
 
3766
               ),
3789
3767
        Option('preview', help='Instead of merging, show a diff of the'
3790
3768
               ' merge.'),
3791
3769
        Option('interactive', help='Select changes interactively.',
3824
3802
            unversioned_filter=tree.is_ignored, view_info=view_info)
3825
3803
        pb = ui.ui_factory.nested_progress_bar()
3826
3804
        self.add_cleanup(pb.finished)
3827
 
        self.add_cleanup(tree.lock_write().unlock)
 
3805
        tree.lock_write()
 
3806
        self.add_cleanup(tree.unlock)
3828
3807
        if location is not None:
3829
3808
            try:
3830
3809
                mergeable = bundle.read_mergeable_from_url(location,
3891
3870
    def _do_preview(self, merger):
3892
3871
        from bzrlib.diff import show_diff_trees
3893
3872
        result_tree = self._get_preview(merger)
3894
 
        path_encoding = osutils.get_diff_header_encoding()
3895
3873
        show_diff_trees(merger.this_tree, result_tree, self.outf,
3896
 
                        old_label='', new_label='',
3897
 
                        path_encoding=path_encoding)
 
3874
                        old_label='', new_label='')
3898
3875
 
3899
3876
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3900
3877
        merger.change_reporter = change_reporter
4053
4030
 
4054
4031
 
4055
4032
class cmd_remerge(Command):
4056
 
    __doc__ = """Redo a merge.
 
4033
    """Redo a merge.
4057
4034
 
4058
4035
    Use this if you want to try a different merge technique while resolving
4059
4036
    conflicts.  Some merge techniques are better than others, and remerge
4084
4061
 
4085
4062
    def run(self, file_list=None, merge_type=None, show_base=False,
4086
4063
            reprocess=False):
4087
 
        from bzrlib.conflicts import restore
4088
4064
        if merge_type is None:
4089
4065
            merge_type = _mod_merge.Merge3Merger
4090
4066
        tree, file_list = tree_files(file_list)
4091
 
        self.add_cleanup(tree.lock_write().unlock)
 
4067
        tree.lock_write()
 
4068
        self.add_cleanup(tree.unlock)
4092
4069
        parents = tree.get_parent_ids()
4093
4070
        if len(parents) != 2:
4094
4071
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4147
4124
 
4148
4125
 
4149
4126
class cmd_revert(Command):
4150
 
    __doc__ = """Revert files to a previous revision.
 
4127
    """Revert files to a previous revision.
4151
4128
 
4152
4129
    Giving a list of files will revert only those files.  Otherwise, all files
4153
4130
    will be reverted.  If the revision is not specified with '--revision', the
4204
4181
    def run(self, revision=None, no_backup=False, file_list=None,
4205
4182
            forget_merges=None):
4206
4183
        tree, file_list = tree_files(file_list)
4207
 
        self.add_cleanup(tree.lock_tree_write().unlock)
 
4184
        tree.lock_write()
 
4185
        self.add_cleanup(tree.unlock)
4208
4186
        if forget_merges:
4209
4187
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4210
4188
        else:
4218
4196
 
4219
4197
 
4220
4198
class cmd_assert_fail(Command):
4221
 
    __doc__ = """Test reporting of assertion failures"""
 
4199
    """Test reporting of assertion failures"""
4222
4200
    # intended just for use in testing
4223
4201
 
4224
4202
    hidden = True
4228
4206
 
4229
4207
 
4230
4208
class cmd_help(Command):
4231
 
    __doc__ = """Show help on a command or other topic.
 
4209
    """Show help on a command or other topic.
4232
4210
    """
4233
4211
 
4234
4212
    _see_also = ['topics']
4247
4225
 
4248
4226
 
4249
4227
class cmd_shell_complete(Command):
4250
 
    __doc__ = """Show appropriate completions for context.
 
4228
    """Show appropriate completions for context.
4251
4229
 
4252
4230
    For a list of all available commands, say 'bzr shell-complete'.
4253
4231
    """
4262
4240
 
4263
4241
 
4264
4242
class cmd_missing(Command):
4265
 
    __doc__ = """Show unmerged/unpulled revisions between two branches.
 
4243
    """Show unmerged/unpulled revisions between two branches.
4266
4244
 
4267
4245
    OTHER_BRANCH may be local or remote.
4268
4246
 
4299
4277
    _see_also = ['merge', 'pull']
4300
4278
    takes_args = ['other_branch?']
4301
4279
    takes_options = [
4302
 
        'directory',
4303
4280
        Option('reverse', 'Reverse the order of revisions.'),
4304
4281
        Option('mine-only',
4305
4282
               'Display changes in the local branch only.'),
4327
4304
            theirs_only=False,
4328
4305
            log_format=None, long=False, short=False, line=False,
4329
4306
            show_ids=False, verbose=False, this=False, other=False,
4330
 
            include_merges=False, revision=None, my_revision=None,
4331
 
            directory=u'.'):
 
4307
            include_merges=False, revision=None, my_revision=None):
4332
4308
        from bzrlib.missing import find_unmerged, iter_log_revisions
4333
4309
        def message(s):
4334
4310
            if not is_quiet():
4347
4323
        elif theirs_only:
4348
4324
            restrict = 'remote'
4349
4325
 
4350
 
        local_branch = Branch.open_containing(directory)[0]
4351
 
        self.add_cleanup(local_branch.lock_read().unlock)
4352
 
 
 
4326
        local_branch = Branch.open_containing(u".")[0]
4353
4327
        parent = local_branch.get_parent()
4354
4328
        if other_branch is None:
4355
4329
            other_branch = parent
4364
4338
        remote_branch = Branch.open(other_branch)
4365
4339
        if remote_branch.base == local_branch.base:
4366
4340
            remote_branch = local_branch
4367
 
        else:
4368
 
            self.add_cleanup(remote_branch.lock_read().unlock)
4369
4341
 
 
4342
        local_branch.lock_read()
 
4343
        self.add_cleanup(local_branch.unlock)
4370
4344
        local_revid_range = _revision_range_to_revid_range(
4371
4345
            _get_revision_range(my_revision, local_branch,
4372
4346
                self.name()))
4373
4347
 
 
4348
        remote_branch.lock_read()
 
4349
        self.add_cleanup(remote_branch.unlock)
4374
4350
        remote_revid_range = _revision_range_to_revid_range(
4375
4351
            _get_revision_range(revision,
4376
4352
                remote_branch, self.name()))
4426
4402
            message("Branches are up to date.\n")
4427
4403
        self.cleanup_now()
4428
4404
        if not status_code and parent is None and other_branch is not None:
4429
 
            self.add_cleanup(local_branch.lock_write().unlock)
 
4405
            local_branch.lock_write()
 
4406
            self.add_cleanup(local_branch.unlock)
4430
4407
            # handle race conditions - a parent might be set while we run.
4431
4408
            if local_branch.get_parent() is None:
4432
4409
                local_branch.set_parent(remote_branch.base)
4434
4411
 
4435
4412
 
4436
4413
class cmd_pack(Command):
4437
 
    __doc__ = """Compress the data within a repository.
4438
 
 
4439
 
    This operation compresses the data within a bazaar repository. As
4440
 
    bazaar supports automatic packing of repository, this operation is
4441
 
    normally not required to be done manually.
4442
 
 
4443
 
    During the pack operation, bazaar takes a backup of existing repository
4444
 
    data, i.e. pack files. This backup is eventually removed by bazaar
4445
 
    automatically when it is safe to do so. To save disk space by removing
4446
 
    the backed up pack files, the --clean-obsolete-packs option may be
4447
 
    used.
4448
 
 
4449
 
    Warning: If you use --clean-obsolete-packs and your machine crashes
4450
 
    during or immediately after repacking, you may be left with a state
4451
 
    where the deletion has been written to disk but the new packs have not
4452
 
    been. In this case the repository may be unusable.
4453
 
    """
 
4414
    """Compress the data within a repository."""
4454
4415
 
4455
4416
    _see_also = ['repositories']
4456
4417
    takes_args = ['branch_or_repo?']
4457
 
    takes_options = [
4458
 
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4459
 
        ]
4460
4418
 
4461
 
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
 
4419
    def run(self, branch_or_repo='.'):
4462
4420
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4463
4421
        try:
4464
4422
            branch = dir.open_branch()
4465
4423
            repository = branch.repository
4466
4424
        except errors.NotBranchError:
4467
4425
            repository = dir.open_repository()
4468
 
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
4426
        repository.pack()
4469
4427
 
4470
4428
 
4471
4429
class cmd_plugins(Command):
4472
 
    __doc__ = """List the installed plugins.
 
4430
    """List the installed plugins.
4473
4431
 
4474
4432
    This command displays the list of installed plugins including
4475
4433
    version of plugin and a short description of each.
4514
4472
 
4515
4473
 
4516
4474
class cmd_testament(Command):
4517
 
    __doc__ = """Show testament (signing-form) of a revision."""
 
4475
    """Show testament (signing-form) of a revision."""
4518
4476
    takes_options = [
4519
4477
            'revision',
4520
4478
            Option('long', help='Produce long-format testament.'),
4532
4490
            b = Branch.open_containing(branch)[0]
4533
4491
        else:
4534
4492
            b = Branch.open(branch)
4535
 
        self.add_cleanup(b.lock_read().unlock)
 
4493
        b.lock_read()
 
4494
        self.add_cleanup(b.unlock)
4536
4495
        if revision is None:
4537
4496
            rev_id = b.last_revision()
4538
4497
        else:
4545
4504
 
4546
4505
 
4547
4506
class cmd_annotate(Command):
4548
 
    __doc__ = """Show the origin of each line in a file.
 
4507
    """Show the origin of each line in a file.
4549
4508
 
4550
4509
    This prints out the given file with an annotation on the left side
4551
4510
    indicating which revision, author and date introduced the change.
4562
4521
                     Option('long', help='Show commit date in annotations.'),
4563
4522
                     'revision',
4564
4523
                     'show-ids',
4565
 
                     'directory',
4566
4524
                     ]
4567
4525
    encoding_type = 'exact'
4568
4526
 
4569
4527
    @display_command
4570
4528
    def run(self, filename, all=False, long=False, revision=None,
4571
 
            show_ids=False, directory=None):
 
4529
            show_ids=False):
4572
4530
        from bzrlib.annotate import annotate_file, annotate_file_tree
4573
4531
        wt, branch, relpath = \
4574
 
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4532
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
4575
4533
        if wt is not None:
4576
 
            self.add_cleanup(wt.lock_read().unlock)
 
4534
            wt.lock_read()
 
4535
            self.add_cleanup(wt.unlock)
4577
4536
        else:
4578
 
            self.add_cleanup(branch.lock_read().unlock)
 
4537
            branch.lock_read()
 
4538
            self.add_cleanup(branch.unlock)
4579
4539
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4580
 
        self.add_cleanup(tree.lock_read().unlock)
 
4540
        tree.lock_read()
 
4541
        self.add_cleanup(tree.unlock)
4581
4542
        if wt is not None:
4582
4543
            file_id = wt.path2id(relpath)
4583
4544
        else:
4596
4557
 
4597
4558
 
4598
4559
class cmd_re_sign(Command):
4599
 
    __doc__ = """Create a digital signature for an existing revision."""
 
4560
    """Create a digital signature for an existing revision."""
4600
4561
    # TODO be able to replace existing ones.
4601
4562
 
4602
4563
    hidden = True # is this right ?
4603
4564
    takes_args = ['revision_id*']
4604
 
    takes_options = ['directory', 'revision']
 
4565
    takes_options = ['revision']
4605
4566
 
4606
 
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
 
4567
    def run(self, revision_id_list=None, revision=None):
4607
4568
        if revision_id_list is not None and revision is not None:
4608
4569
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4609
4570
        if revision_id_list is None and revision is None:
4610
4571
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4611
 
        b = WorkingTree.open_containing(directory)[0].branch
4612
 
        self.add_cleanup(b.lock_write().unlock)
 
4572
        b = WorkingTree.open_containing(u'.')[0].branch
 
4573
        b.lock_write()
 
4574
        self.add_cleanup(b.unlock)
4613
4575
        return self._run(b, revision_id_list, revision)
4614
4576
 
4615
4577
    def _run(self, b, revision_id_list, revision):
4661
4623
 
4662
4624
 
4663
4625
class cmd_bind(Command):
4664
 
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
4665
 
    If no branch is supplied, rebind to the last bound location.
 
4626
    """Convert the current branch into a checkout of the supplied branch.
4666
4627
 
4667
4628
    Once converted into a checkout, commits must succeed on the master branch
4668
4629
    before they will be applied to the local branch.
4674
4635
 
4675
4636
    _see_also = ['checkouts', 'unbind']
4676
4637
    takes_args = ['location?']
4677
 
    takes_options = ['directory']
 
4638
    takes_options = []
4678
4639
 
4679
 
    def run(self, location=None, directory=u'.'):
4680
 
        b, relpath = Branch.open_containing(directory)
 
4640
    def run(self, location=None):
 
4641
        b, relpath = Branch.open_containing(u'.')
4681
4642
        if location is None:
4682
4643
            try:
4683
4644
                location = b.get_old_bound_location()
4702
4663
 
4703
4664
 
4704
4665
class cmd_unbind(Command):
4705
 
    __doc__ = """Convert the current checkout into a regular branch.
 
4666
    """Convert the current checkout into a regular branch.
4706
4667
 
4707
4668
    After unbinding, the local branch is considered independent and subsequent
4708
4669
    commits will be local only.
4710
4671
 
4711
4672
    _see_also = ['checkouts', 'bind']
4712
4673
    takes_args = []
4713
 
    takes_options = ['directory']
 
4674
    takes_options = []
4714
4675
 
4715
 
    def run(self, directory=u'.'):
4716
 
        b, relpath = Branch.open_containing(directory)
 
4676
    def run(self):
 
4677
        b, relpath = Branch.open_containing(u'.')
4717
4678
        if not b.unbind():
4718
4679
            raise errors.BzrCommandError('Local branch is not bound')
4719
4680
 
4720
4681
 
4721
4682
class cmd_uncommit(Command):
4722
 
    __doc__ = """Remove the last committed revision.
 
4683
    """Remove the last committed revision.
4723
4684
 
4724
4685
    --verbose will print out what is being removed.
4725
4686
    --dry-run will go through all the motions, but not actually
4765
4726
            b = control.open_branch()
4766
4727
 
4767
4728
        if tree is not None:
4768
 
            self.add_cleanup(tree.lock_write().unlock)
 
4729
            tree.lock_write()
 
4730
            self.add_cleanup(tree.unlock)
4769
4731
        else:
4770
 
            self.add_cleanup(b.lock_write().unlock)
 
4732
            b.lock_write()
 
4733
            self.add_cleanup(b.unlock)
4771
4734
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4772
4735
 
4773
4736
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4825
4788
 
4826
4789
 
4827
4790
class cmd_break_lock(Command):
4828
 
    __doc__ = """Break a dead lock on a repository, branch or working directory.
 
4791
    """Break a dead lock on a repository, branch or working directory.
4829
4792
 
4830
4793
    CAUTION: Locks should only be broken when you are sure that the process
4831
4794
    holding the lock has been stopped.
4850
4813
 
4851
4814
 
4852
4815
class cmd_wait_until_signalled(Command):
4853
 
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4816
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4854
4817
 
4855
4818
    This just prints a line to signal when it is ready, then blocks on stdin.
4856
4819
    """
4864
4827
 
4865
4828
 
4866
4829
class cmd_serve(Command):
4867
 
    __doc__ = """Run the bzr server."""
 
4830
    """Run the bzr server."""
4868
4831
 
4869
4832
    aliases = ['server']
4870
4833
 
4881
4844
                    'result in a dynamically allocated port.  The default port '
4882
4845
                    'depends on the protocol.',
4883
4846
               type=str),
4884
 
        custom_help('directory',
4885
 
               help='Serve contents of this directory.'),
 
4847
        Option('directory',
 
4848
               help='Serve contents of this directory.',
 
4849
               type=unicode),
4886
4850
        Option('allow-writes',
4887
4851
               help='By default the server is a readonly server.  Supplying '
4888
4852
                    '--allow-writes enables write access to the contents of '
4915
4879
 
4916
4880
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
4917
4881
            protocol=None):
4918
 
        from bzrlib import transport
 
4882
        from bzrlib.transport import get_transport, transport_server_registry
4919
4883
        if directory is None:
4920
4884
            directory = os.getcwd()
4921
4885
        if protocol is None:
4922
 
            protocol = transport.transport_server_registry.get()
 
4886
            protocol = transport_server_registry.get()
4923
4887
        host, port = self.get_host_and_port(port)
4924
4888
        url = urlutils.local_path_to_url(directory)
4925
4889
        if not allow_writes:
4926
4890
            url = 'readonly+' + url
4927
 
        t = transport.get_transport(url)
4928
 
        protocol(t, host, port, inet)
 
4891
        transport = get_transport(url)
 
4892
        protocol(transport, host, port, inet)
4929
4893
 
4930
4894
 
4931
4895
class cmd_join(Command):
4932
 
    __doc__ = """Combine a tree into its containing tree.
 
4896
    """Combine a tree into its containing tree.
4933
4897
 
4934
4898
    This command requires the target tree to be in a rich-root format.
4935
4899
 
4975
4939
 
4976
4940
 
4977
4941
class cmd_split(Command):
4978
 
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
4942
    """Split a subdirectory of a tree into a separate tree.
4979
4943
 
4980
4944
    This command will produce a target tree in a format that supports
4981
4945
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
5001
4965
 
5002
4966
 
5003
4967
class cmd_merge_directive(Command):
5004
 
    __doc__ = """Generate a merge directive for auto-merge tools.
 
4968
    """Generate a merge directive for auto-merge tools.
5005
4969
 
5006
4970
    A directive requests a merge to be performed, and also provides all the
5007
4971
    information necessary to do so.  This means it must either include a
5024
4988
    _see_also = ['send']
5025
4989
 
5026
4990
    takes_options = [
5027
 
        'directory',
5028
4991
        RegistryOption.from_kwargs('patch-type',
5029
4992
            'The type of patch to include in the directive.',
5030
4993
            title='Patch type',
5043
5006
    encoding_type = 'exact'
5044
5007
 
5045
5008
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5046
 
            sign=False, revision=None, mail_to=None, message=None,
5047
 
            directory=u'.'):
 
5009
            sign=False, revision=None, mail_to=None, message=None):
5048
5010
        from bzrlib.revision import ensure_null, NULL_REVISION
5049
5011
        include_patch, include_bundle = {
5050
5012
            'plain': (False, False),
5051
5013
            'diff': (True, False),
5052
5014
            'bundle': (True, True),
5053
5015
            }[patch_type]
5054
 
        branch = Branch.open(directory)
 
5016
        branch = Branch.open('.')
5055
5017
        stored_submit_branch = branch.get_submit_branch()
5056
5018
        if submit_branch is None:
5057
5019
            submit_branch = stored_submit_branch
5102
5064
 
5103
5065
 
5104
5066
class cmd_send(Command):
5105
 
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
5067
    """Mail or create a merge-directive for submitting changes.
5106
5068
 
5107
5069
    A merge directive provides many things needed for requesting merges:
5108
5070
 
5142
5104
    given, in which case it is sent to a file.
5143
5105
 
5144
5106
    Mail is sent using your preferred mail program.  This should be transparent
5145
 
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
5107
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
5146
5108
    If the preferred client can't be found (or used), your editor will be used.
5147
5109
 
5148
5110
    To use a specific mail program, set the mail_client configuration option.
5219
5181
 
5220
5182
 
5221
5183
class cmd_bundle_revisions(cmd_send):
5222
 
    __doc__ = """Create a merge-directive for submitting changes.
 
5184
    """Create a merge-directive for submitting changes.
5223
5185
 
5224
5186
    A merge directive provides many things needed for requesting merges:
5225
5187
 
5292
5254
 
5293
5255
 
5294
5256
class cmd_tag(Command):
5295
 
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5257
    """Create, remove or modify a tag naming a revision.
5296
5258
 
5297
5259
    Tags give human-meaningful names to revisions.  Commands that take a -r
5298
5260
    (--revision) option can be given -rtag:X, where X is any previously
5319
5281
        Option('delete',
5320
5282
            help='Delete this tag rather than placing it.',
5321
5283
            ),
5322
 
        custom_help('directory',
5323
 
            help='Branch in which to place the tag.'),
 
5284
        Option('directory',
 
5285
            help='Branch in which to place the tag.',
 
5286
            short_name='d',
 
5287
            type=unicode,
 
5288
            ),
5324
5289
        Option('force',
5325
5290
            help='Replace existing tags.',
5326
5291
            ),
5334
5299
            revision=None,
5335
5300
            ):
5336
5301
        branch, relpath = Branch.open_containing(directory)
5337
 
        self.add_cleanup(branch.lock_write().unlock)
 
5302
        branch.lock_write()
 
5303
        self.add_cleanup(branch.unlock)
5338
5304
        if delete:
5339
5305
            if tag_name is None:
5340
5306
                raise errors.BzrCommandError("No tag specified to delete.")
5361
5327
 
5362
5328
 
5363
5329
class cmd_tags(Command):
5364
 
    __doc__ = """List tags.
 
5330
    """List tags.
5365
5331
 
5366
5332
    This command shows a table of tag names and the revisions they reference.
5367
5333
    """
5368
5334
 
5369
5335
    _see_also = ['tag']
5370
5336
    takes_options = [
5371
 
        custom_help('directory',
5372
 
            help='Branch whose tags should be displayed.'),
 
5337
        Option('directory',
 
5338
            help='Branch whose tags should be displayed.',
 
5339
            short_name='d',
 
5340
            type=unicode,
 
5341
            ),
5373
5342
        RegistryOption.from_kwargs('sort',
5374
5343
            'Sort tags by different criteria.', title='Sorting',
5375
5344
            alpha='Sort tags lexicographically (default).',
5392
5361
        if not tags:
5393
5362
            return
5394
5363
 
5395
 
        self.add_cleanup(branch.lock_read().unlock)
 
5364
        branch.lock_read()
 
5365
        self.add_cleanup(branch.unlock)
5396
5366
        if revision:
5397
5367
            graph = branch.repository.get_graph()
5398
5368
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
5431
5401
 
5432
5402
 
5433
5403
class cmd_reconfigure(Command):
5434
 
    __doc__ = """Reconfigure the type of a bzr directory.
 
5404
    """Reconfigure the type of a bzr directory.
5435
5405
 
5436
5406
    A target configuration must be specified.
5437
5407
 
5522
5492
 
5523
5493
 
5524
5494
class cmd_switch(Command):
5525
 
    __doc__ = """Set the branch of a checkout and update.
 
5495
    """Set the branch of a checkout and update.
5526
5496
 
5527
5497
    For lightweight checkouts, this changes the branch being referenced.
5528
5498
    For heavyweight checkouts, this checks that there are no local commits
5545
5515
    """
5546
5516
 
5547
5517
    takes_args = ['to_location?']
5548
 
    takes_options = ['directory',
5549
 
                     Option('force',
 
5518
    takes_options = [Option('force',
5550
5519
                        help='Switch even if local commits will be lost.'),
5551
5520
                     'revision',
5552
5521
                     Option('create-branch', short_name='b',
5555
5524
                    ]
5556
5525
 
5557
5526
    def run(self, to_location=None, force=False, create_branch=False,
5558
 
            revision=None, directory=u'.'):
 
5527
            revision=None):
5559
5528
        from bzrlib import switch
5560
 
        tree_location = directory
 
5529
        tree_location = '.'
5561
5530
        revision = _get_one_revision('switch', revision)
5562
5531
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5563
5532
        if to_location is None:
5564
5533
            if revision is None:
5565
5534
                raise errors.BzrCommandError('You must supply either a'
5566
5535
                                             ' revision or a location')
5567
 
            to_location = tree_location
 
5536
            to_location = '.'
5568
5537
        try:
5569
5538
            branch = control_dir.open_branch()
5570
5539
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5619
5588
 
5620
5589
 
5621
5590
class cmd_view(Command):
5622
 
    __doc__ = """Manage filtered views.
 
5591
    """Manage filtered views.
5623
5592
 
5624
5593
    Views provide a mask over the tree so that users can focus on
5625
5594
    a subset of a tree when doing their work. After creating a view,
5773
5742
 
5774
5743
 
5775
5744
class cmd_hooks(Command):
5776
 
    __doc__ = """Show hooks."""
 
5745
    """Show hooks."""
5777
5746
 
5778
5747
    hidden = True
5779
5748
 
5793
5762
 
5794
5763
 
5795
5764
class cmd_remove_branch(Command):
5796
 
    __doc__ = """Remove a branch.
 
5765
    """Remove a branch.
5797
5766
 
5798
5767
    This will remove the branch from the specified location but 
5799
5768
    will keep any working tree or repository in place.
5818
5787
        
5819
5788
 
5820
5789
class cmd_shelve(Command):
5821
 
    __doc__ = """Temporarily set aside some changes from the current tree.
 
5790
    """Temporarily set aside some changes from the current tree.
5822
5791
 
5823
5792
    Shelve allows you to temporarily put changes you've made "on the shelf",
5824
5793
    ie. out of the way, until a later time when you can bring them back from
5845
5814
    takes_args = ['file*']
5846
5815
 
5847
5816
    takes_options = [
5848
 
        'directory',
5849
5817
        'revision',
5850
5818
        Option('all', help='Shelve all changes.'),
5851
5819
        'message',
5860
5828
    _see_also = ['unshelve']
5861
5829
 
5862
5830
    def run(self, revision=None, all=False, file_list=None, message=None,
5863
 
            writer=None, list=False, destroy=False, directory=u'.'):
 
5831
            writer=None, list=False, destroy=False):
5864
5832
        if list:
5865
5833
            return self.run_for_list()
5866
5834
        from bzrlib.shelf_ui import Shelver
5868
5836
            writer = bzrlib.option.diff_writer_registry.get()
5869
5837
        try:
5870
5838
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5871
 
                file_list, message, destroy=destroy, directory=directory)
 
5839
                file_list, message, destroy=destroy)
5872
5840
            try:
5873
5841
                shelver.run()
5874
5842
            finally:
5878
5846
 
5879
5847
    def run_for_list(self):
5880
5848
        tree = WorkingTree.open_containing('.')[0]
5881
 
        self.add_cleanup(tree.lock_read().unlock)
 
5849
        tree.lock_read()
 
5850
        self.add_cleanup(tree.unlock)
5882
5851
        manager = tree.get_shelf_manager()
5883
5852
        shelves = manager.active_shelves()
5884
5853
        if len(shelves) == 0:
5893
5862
 
5894
5863
 
5895
5864
class cmd_unshelve(Command):
5896
 
    __doc__ = """Restore shelved changes.
 
5865
    """Restore shelved changes.
5897
5866
 
5898
5867
    By default, the most recently shelved changes are restored. However if you
5899
5868
    specify a shelf by id those changes will be restored instead.  This works
5902
5871
 
5903
5872
    takes_args = ['shelf_id?']
5904
5873
    takes_options = [
5905
 
        'directory',
5906
5874
        RegistryOption.from_kwargs(
5907
5875
            'action', help="The action to perform.",
5908
5876
            enum_switch=False, value_switches=True,
5916
5884
    ]
5917
5885
    _see_also = ['shelve']
5918
5886
 
5919
 
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
5887
    def run(self, shelf_id=None, action='apply'):
5920
5888
        from bzrlib.shelf_ui import Unshelver
5921
 
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
5889
        unshelver = Unshelver.from_args(shelf_id, action)
5922
5890
        try:
5923
5891
            unshelver.run()
5924
5892
        finally:
5926
5894
 
5927
5895
 
5928
5896
class cmd_clean_tree(Command):
5929
 
    __doc__ = """Remove unwanted files from working tree.
 
5897
    """Remove unwanted files from working tree.
5930
5898
 
5931
5899
    By default, only unknown files, not ignored files, are deleted.  Versioned
5932
5900
    files are never deleted.
5940
5908
 
5941
5909
    To check what clean-tree will do, use --dry-run.
5942
5910
    """
5943
 
    takes_options = ['directory',
5944
 
                     Option('ignored', help='Delete all ignored files.'),
 
5911
    takes_options = [Option('ignored', help='Delete all ignored files.'),
5945
5912
                     Option('detritus', help='Delete conflict files, merge'
5946
5913
                            ' backups, and failed selftest dirs.'),
5947
5914
                     Option('unknown',
5950
5917
                            ' deleting them.'),
5951
5918
                     Option('force', help='Do not prompt before deleting.')]
5952
5919
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5953
 
            force=False, directory=u'.'):
 
5920
            force=False):
5954
5921
        from bzrlib.clean_tree import clean_tree
5955
5922
        if not (unknown or ignored or detritus):
5956
5923
            unknown = True
5957
5924
        if dry_run:
5958
5925
            force = True
5959
 
        clean_tree(directory, unknown=unknown, ignored=ignored,
5960
 
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5926
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
 
5927
                   dry_run=dry_run, no_prompt=force)
5961
5928
 
5962
5929
 
5963
5930
class cmd_reference(Command):
5964
 
    __doc__ = """list, view and set branch locations for nested trees.
 
5931
    """list, view and set branch locations for nested trees.
5965
5932
 
5966
5933
    If no arguments are provided, lists the branch locations for nested trees.
5967
5934
    If one argument is provided, display the branch location for that tree.
6007
5974
            self.outf.write('%s %s\n' % (path, location))
6008
5975
 
6009
5976
 
6010
 
def _register_lazy_builtins():
6011
 
    # register lazy builtins from other modules; called at startup and should
6012
 
    # be only called once.
6013
 
    for (name, aliases, module_name) in [
6014
 
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6015
 
        ('cmd_dpush', [], 'bzrlib.foreign'),
6016
 
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6017
 
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6018
 
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
6019
 
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6020
 
        ]:
6021
 
        builtin_command_registry.register_lazy(name, aliases, module_name)
 
5977
from bzrlib.cmd_version_info import cmd_version_info
 
5978
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
5979
from bzrlib.foreign import cmd_dpush
 
5980
from bzrlib.sign_my_commits import cmd_sign_my_commits