~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Andrew Bennetts
  • Date: 2010-06-16 05:47:02 UTC
  • mto: This revision was merged to the branch mainline in revision 5299.
  • Revision ID: andrew.bennetts@canonical.com-20100616054702-hho3e72ebs7biki8
Use socketpairs (rather than pipes) for SSH subprocesses where possible, and formalise some internal APIs a little more.

Show diffs side-by-side

added added

removed removed

Lines of Context:
232
232
    return view_info
233
233
 
234
234
 
 
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
 
235
243
# TODO: Make sure no commands unconditionally use the working directory as a
236
244
# branch.  If a filename argument is used, the first of them should be used to
237
245
# specify the branch.  (Perhaps this can be factored out into some kind of
340
348
 
341
349
    hidden = True
342
350
    takes_args = ['revision_id?']
343
 
    takes_options = ['revision']
 
351
    takes_options = ['directory', 'revision']
344
352
    # cat-revision is more for frontends so should be exact
345
353
    encoding = 'strict'
346
354
 
353
361
        self.outf.write(revtext.decode('utf-8'))
354
362
 
355
363
    @display_command
356
 
    def run(self, revision_id=None, revision=None):
 
364
    def run(self, revision_id=None, revision=None, directory=u'.'):
357
365
        if revision_id is not None and revision is not None:
358
366
            raise errors.BzrCommandError('You can only supply one of'
359
367
                                         ' revision_id or --revision')
360
368
        if revision_id is None and revision is None:
361
369
            raise errors.BzrCommandError('You must supply either'
362
370
                                         ' --revision or a revision_id')
363
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
371
        b = WorkingTree.open_containing(directory)[0].branch
364
372
 
365
373
        revisions = b.repository.revisions
366
374
        if revisions is None:
483
491
    takes_options = [
484
492
        Option('force',
485
493
               help='Remove the working tree even if it has '
486
 
                    'uncommitted changes.'),
 
494
                    'uncommitted or shelved changes.'),
487
495
        ]
488
496
 
489
497
    def run(self, location_list, force=False):
503
511
            if not force:
504
512
                if (working.has_changes()):
505
513
                    raise errors.UncommittedChanges(working)
 
514
                if working.get_shelf_manager().last_shelf() is not None:
 
515
                    raise errors.ShelvedChanges(working)
506
516
 
507
517
            if working.user_url != working.branch.user_url:
508
518
                raise errors.BzrCommandError("You cannot remove the working tree"
528
538
        if tree:
529
539
            try:
530
540
                wt = WorkingTree.open_containing(location)[0]
531
 
                wt.lock_read()
 
541
                self.add_cleanup(wt.lock_read().unlock)
532
542
            except (errors.NoWorkingTree, errors.NotLocalUrl):
533
543
                raise errors.NoWorkingTree(location)
534
 
            self.add_cleanup(wt.unlock)
535
544
            revid = wt.last_revision()
536
545
            try:
537
546
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
540
549
            revno = ".".join(str(n) for n in revno_t)
541
550
        else:
542
551
            b = Branch.open_containing(location)[0]
543
 
            b.lock_read()
544
 
            self.add_cleanup(b.unlock)
 
552
            self.add_cleanup(b.lock_read().unlock)
545
553
            revno = b.revno()
546
554
        self.cleanup_now()
547
555
        self.outf.write(str(revno) + '\n')
554
562
    takes_args = ['revision_info*']
555
563
    takes_options = [
556
564
        'revision',
557
 
        Option('directory',
 
565
        custom_help('directory',
558
566
            help='Branch to examine, '
559
 
                 'rather than the one containing the working directory.',
560
 
            short_name='d',
561
 
            type=unicode,
562
 
            ),
 
567
                 'rather than the one containing the working directory.'),
563
568
        Option('tree', help='Show revno of working tree'),
564
569
        ]
565
570
 
570
575
        try:
571
576
            wt = WorkingTree.open_containing(directory)[0]
572
577
            b = wt.branch
573
 
            wt.lock_read()
574
 
            self.add_cleanup(wt.unlock)
 
578
            self.add_cleanup(wt.lock_read().unlock)
575
579
        except (errors.NoWorkingTree, errors.NotLocalUrl):
576
580
            wt = None
577
581
            b = Branch.open_containing(directory)[0]
578
 
            b.lock_read()
579
 
            self.add_cleanup(b.unlock)
 
582
            self.add_cleanup(b.lock_read().unlock)
580
583
        revision_ids = []
581
584
        if revision is not None:
582
585
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
681
684
                should_print=(not is_quiet()))
682
685
 
683
686
        if base_tree:
684
 
            base_tree.lock_read()
685
 
            self.add_cleanup(base_tree.unlock)
 
687
            self.add_cleanup(base_tree.lock_read().unlock)
686
688
        tree, file_list = tree_files_for_add(file_list)
687
689
        added, ignored = tree.smart_add(file_list, not
688
690
            no_recurse, action=action, save=not dry_run)
760
762
 
761
763
        revision = _get_one_revision('inventory', revision)
762
764
        work_tree, file_list = tree_files(file_list)
763
 
        work_tree.lock_read()
764
 
        self.add_cleanup(work_tree.unlock)
 
765
        self.add_cleanup(work_tree.lock_read().unlock)
765
766
        if revision is not None:
766
767
            tree = revision.as_tree(work_tree.branch)
767
768
 
768
769
            extra_trees = [work_tree]
769
 
            tree.lock_read()
770
 
            self.add_cleanup(tree.unlock)
 
770
            self.add_cleanup(tree.lock_read().unlock)
771
771
        else:
772
772
            tree = work_tree
773
773
            extra_trees = []
833
833
        if len(names_list) < 2:
834
834
            raise errors.BzrCommandError("missing file argument")
835
835
        tree, rel_names = tree_files(names_list, canonicalize=False)
836
 
        tree.lock_tree_write()
837
 
        self.add_cleanup(tree.unlock)
 
836
        self.add_cleanup(tree.lock_tree_write().unlock)
838
837
        self._run(tree, names_list, rel_names, after)
839
838
 
840
839
    def run_auto(self, names_list, after, dry_run):
845
844
            raise errors.BzrCommandError('--after cannot be specified with'
846
845
                                         ' --auto.')
847
846
        work_tree, file_list = tree_files(names_list, default_branch='.')
848
 
        work_tree.lock_tree_write()
849
 
        self.add_cleanup(work_tree.unlock)
 
847
        self.add_cleanup(work_tree.lock_tree_write().unlock)
850
848
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
851
849
 
852
850
    def _run(self, tree, names_list, rel_names, after):
960
958
    takes_options = ['remember', 'overwrite', 'revision',
961
959
        custom_help('verbose',
962
960
            help='Show logs of pulled revisions.'),
963
 
        Option('directory',
 
961
        custom_help('directory',
964
962
            help='Branch to pull into, '
965
 
                 'rather than the one containing the working directory.',
966
 
            short_name='d',
967
 
            type=unicode,
968
 
            ),
 
963
                 'rather than the one containing the working directory.'),
969
964
        Option('local',
970
965
            help="Perform a local pull in a bound "
971
966
                 "branch.  Local pulls are not applied to "
986
981
        try:
987
982
            tree_to = WorkingTree.open_containing(directory)[0]
988
983
            branch_to = tree_to.branch
989
 
            tree_to.lock_write()
990
 
            self.add_cleanup(tree_to.unlock)
 
984
            self.add_cleanup(tree_to.lock_write().unlock)
991
985
        except errors.NoWorkingTree:
992
986
            tree_to = None
993
987
            branch_to = Branch.open_containing(directory)[0]
994
 
            branch_to.lock_write()
995
 
            self.add_cleanup(branch_to.unlock)
 
988
            self.add_cleanup(branch_to.lock_write().unlock)
996
989
 
997
990
        if local and not branch_to.get_bound_location():
998
991
            raise errors.LocalRequiresBoundBranch()
1029
1022
        else:
1030
1023
            branch_from = Branch.open(location,
1031
1024
                possible_transports=possible_transports)
1032
 
            branch_from.lock_read()
1033
 
            self.add_cleanup(branch_from.unlock)
 
1025
            self.add_cleanup(branch_from.lock_read().unlock)
1034
1026
 
1035
1027
            if branch_to.get_parent() is None or remember:
1036
1028
                branch_to.set_parent(branch_from.base)
1088
1080
        Option('create-prefix',
1089
1081
               help='Create the path leading up to the branch '
1090
1082
                    'if it does not already exist.'),
1091
 
        Option('directory',
 
1083
        custom_help('directory',
1092
1084
            help='Branch to push from, '
1093
 
                 'rather than the one containing the working directory.',
1094
 
            short_name='d',
1095
 
            type=unicode,
1096
 
            ),
 
1085
                 'rather than the one containing the working directory.'),
1097
1086
        Option('use-existing-dir',
1098
1087
               help='By default push will fail if the target'
1099
1088
                    ' directory exists, but does not already'
1219
1208
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1220
1209
            from_location)
1221
1210
        revision = _get_one_revision('branch', revision)
1222
 
        br_from.lock_read()
1223
 
        self.add_cleanup(br_from.unlock)
 
1211
        self.add_cleanup(br_from.lock_read().unlock)
1224
1212
        if revision is not None:
1225
1213
            revision_id = revision.as_revision_id(br_from)
1226
1214
        else:
1366
1354
    @display_command
1367
1355
    def run(self, dir=u'.'):
1368
1356
        tree = WorkingTree.open_containing(dir)[0]
1369
 
        tree.lock_read()
1370
 
        self.add_cleanup(tree.unlock)
 
1357
        self.add_cleanup(tree.lock_read().unlock)
1371
1358
        new_inv = tree.inventory
1372
1359
        old_tree = tree.basis_tree()
1373
 
        old_tree.lock_read()
1374
 
        self.add_cleanup(old_tree.unlock)
 
1360
        self.add_cleanup(old_tree.lock_read().unlock)
1375
1361
        old_inv = old_tree.inventory
1376
1362
        renames = []
1377
1363
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1415
1401
        master = branch.get_master_branch(
1416
1402
            possible_transports=possible_transports)
1417
1403
        if master is not None:
1418
 
            tree.lock_write()
1419
1404
            branch_location = master.base
 
1405
            tree.lock_write()
1420
1406
        else:
 
1407
            branch_location = tree.branch.base
1421
1408
            tree.lock_tree_write()
1422
 
            branch_location = tree.branch.base
1423
1409
        self.add_cleanup(tree.unlock)
1424
1410
        # get rid of the final '/' and be ready for display
1425
1411
        branch_location = urlutils.unescape_for_display(
1545
1531
        if file_list is not None:
1546
1532
            file_list = [f for f in file_list]
1547
1533
 
1548
 
        tree.lock_write()
1549
 
        self.add_cleanup(tree.unlock)
 
1534
        self.add_cleanup(tree.lock_write().unlock)
1550
1535
        # Heuristics should probably all move into tree.remove_smart or
1551
1536
        # some such?
1552
1537
        if new:
2003
1988
    # level of effort but possibly much less IO.  (Or possibly not,
2004
1989
    # if the directories are very large...)
2005
1990
    _see_also = ['status', 'ls']
2006
 
    takes_options = ['show-ids']
 
1991
    takes_options = ['directory', 'show-ids']
2007
1992
 
2008
1993
    @display_command
2009
 
    def run(self, show_ids=False):
2010
 
        tree = WorkingTree.open_containing(u'.')[0]
2011
 
        tree.lock_read()
2012
 
        self.add_cleanup(tree.unlock)
 
1994
    def run(self, show_ids=False, directory=u'.'):
 
1995
        tree = WorkingTree.open_containing(directory)[0]
 
1996
        self.add_cleanup(tree.lock_read().unlock)
2013
1997
        old = tree.basis_tree()
2014
 
        old.lock_read()
2015
 
        self.add_cleanup(old.unlock)
 
1998
        self.add_cleanup(old.lock_read().unlock)
2016
1999
        for path, ie in old.inventory.iter_entries():
2017
2000
            if not tree.has_id(ie.file_id):
2018
2001
                self.outf.write(path)
2028
2011
 
2029
2012
    hidden = True
2030
2013
    _see_also = ['status', 'ls']
2031
 
    takes_options = [
2032
 
            Option('null',
2033
 
                   help='Write an ascii NUL (\\0) separator '
2034
 
                   'between files rather than a newline.')
2035
 
            ]
 
2014
    takes_options = ['directory', 'null']
2036
2015
 
2037
2016
    @display_command
2038
 
    def run(self, null=False):
2039
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2017
    def run(self, null=False, directory=u'.'):
 
2018
        tree = WorkingTree.open_containing(directory)[0]
2040
2019
        td = tree.changes_from(tree.basis_tree())
2041
2020
        for path, id, kind, text_modified, meta_modified in td.modified:
2042
2021
            if null:
2051
2030
 
2052
2031
    hidden = True
2053
2032
    _see_also = ['status', 'ls']
2054
 
    takes_options = [
2055
 
            Option('null',
2056
 
                   help='Write an ascii NUL (\\0) separator '
2057
 
                   'between files rather than a newline.')
2058
 
            ]
 
2033
    takes_options = ['directory', 'null']
2059
2034
 
2060
2035
    @display_command
2061
 
    def run(self, null=False):
2062
 
        wt = WorkingTree.open_containing(u'.')[0]
2063
 
        wt.lock_read()
2064
 
        self.add_cleanup(wt.unlock)
 
2036
    def run(self, null=False, directory=u'.'):
 
2037
        wt = WorkingTree.open_containing(directory)[0]
 
2038
        self.add_cleanup(wt.lock_read().unlock)
2065
2039
        basis = wt.basis_tree()
2066
 
        basis.lock_read()
2067
 
        self.add_cleanup(basis.unlock)
 
2040
        self.add_cleanup(basis.lock_read().unlock)
2068
2041
        basis_inv = basis.inventory
2069
2042
        inv = wt.inventory
2070
2043
        for file_id in inv:
2073
2046
            if inv.is_root(file_id) and len(basis_inv) == 0:
2074
2047
                continue
2075
2048
            path = inv.id2path(file_id)
2076
 
            if not os.access(osutils.abspath(path), os.F_OK):
 
2049
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2077
2050
                continue
2078
2051
            if null:
2079
2052
                self.outf.write(path + '\0')
2279
2252
                   help='Show just the specified revision.'
2280
2253
                   ' See also "help revisionspec".'),
2281
2254
            'log-format',
 
2255
            RegistryOption('authors',
 
2256
                'What names to list as authors - first, all or committer.',
 
2257
                title='Authors',
 
2258
                lazy_registry=('bzrlib.log', 'author_list_registry'),
 
2259
            ),
2282
2260
            Option('levels',
2283
2261
                   short_name='n',
2284
2262
                   help='Number of levels to display - 0 for all, 1 for flat.',
2319
2297
            limit=None,
2320
2298
            show_diff=False,
2321
2299
            include_merges=False,
 
2300
            authors=None,
2322
2301
            exclude_common_ancestry=False,
2323
2302
            ):
2324
2303
        from bzrlib.log import (
2352
2331
        if file_list:
2353
2332
            # find the file ids to log and check for directory filtering
2354
2333
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2355
 
                revision, file_list)
2356
 
            self.add_cleanup(b.unlock)
 
2334
                revision, file_list, self.add_cleanup)
2357
2335
            for relpath, file_id, kind in file_info_list:
2358
2336
                if file_id is None:
2359
2337
                    raise errors.BzrCommandError(
2377
2355
                location = '.'
2378
2356
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2379
2357
            b = dir.open_branch()
2380
 
            b.lock_read()
2381
 
            self.add_cleanup(b.unlock)
 
2358
            self.add_cleanup(b.lock_read().unlock)
2382
2359
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2383
2360
 
2384
2361
        # Decide on the type of delta & diff filtering to use
2404
2381
                        show_timezone=timezone,
2405
2382
                        delta_format=get_verbosity_level(),
2406
2383
                        levels=levels,
2407
 
                        show_advice=levels is None)
 
2384
                        show_advice=levels is None,
 
2385
                        author_list_handler=authors)
2408
2386
 
2409
2387
        # Choose the algorithm for doing the logging. It's annoying
2410
2388
        # having multiple code paths like this but necessary until
2508
2486
        tree, relpath = WorkingTree.open_containing(filename)
2509
2487
        file_id = tree.path2id(relpath)
2510
2488
        b = tree.branch
2511
 
        b.lock_read()
2512
 
        self.add_cleanup(b.unlock)
 
2489
        self.add_cleanup(b.lock_read().unlock)
2513
2490
        touching_revs = log.find_touching_revisions(b, file_id)
2514
2491
        for revno, revision_id, what in touching_revs:
2515
2492
            self.outf.write("%6d %s\n" % (revno, what))
2528
2505
                   help='Recurse into subdirectories.'),
2529
2506
            Option('from-root',
2530
2507
                   help='Print paths relative to the root of the branch.'),
2531
 
            Option('unknown', help='Print unknown files.'),
 
2508
            Option('unknown', short_name='u',
 
2509
                help='Print unknown files.'),
2532
2510
            Option('versioned', help='Print versioned files.',
2533
2511
                   short_name='V'),
2534
 
            Option('ignored', help='Print ignored files.'),
2535
 
            Option('null',
2536
 
                   help='Write an ascii NUL (\\0) separator '
2537
 
                   'between files rather than a newline.'),
2538
 
            Option('kind',
 
2512
            Option('ignored', short_name='i',
 
2513
                help='Print ignored files.'),
 
2514
            Option('kind', short_name='k',
2539
2515
                   help='List entries of a particular kind: file, directory, symlink.',
2540
2516
                   type=unicode),
 
2517
            'null',
2541
2518
            'show-ids',
 
2519
            'directory',
2542
2520
            ]
2543
2521
    @display_command
2544
2522
    def run(self, revision=None, verbose=False,
2545
2523
            recursive=False, from_root=False,
2546
2524
            unknown=False, versioned=False, ignored=False,
2547
 
            null=False, kind=None, show_ids=False, path=None):
 
2525
            null=False, kind=None, show_ids=False, path=None, directory=None):
2548
2526
 
2549
2527
        if kind and kind not in ('file', 'directory', 'symlink'):
2550
2528
            raise errors.BzrCommandError('invalid kind specified')
2562
2540
                raise errors.BzrCommandError('cannot specify both --from-root'
2563
2541
                                             ' and PATH')
2564
2542
            fs_path = path
2565
 
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2566
 
            fs_path)
 
2543
        tree, branch, relpath = \
 
2544
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
2567
2545
 
2568
2546
        # Calculate the prefix to use
2569
2547
        prefix = None
2584
2562
                view_str = views.view_display_str(view_files)
2585
2563
                note("Ignoring files outside view. View is %s" % view_str)
2586
2564
 
2587
 
        tree.lock_read()
2588
 
        self.add_cleanup(tree.unlock)
 
2565
        self.add_cleanup(tree.lock_read().unlock)
2589
2566
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2590
2567
            from_dir=relpath, recursive=recursive):
2591
2568
            # Apply additional masking
2638
2615
 
2639
2616
    hidden = True
2640
2617
    _see_also = ['ls']
 
2618
    takes_options = ['directory']
2641
2619
 
2642
2620
    @display_command
2643
 
    def run(self):
2644
 
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
2621
    def run(self, directory=u'.'):
 
2622
        for f in WorkingTree.open_containing(directory)[0].unknowns():
2645
2623
            self.outf.write(osutils.quotefn(f) + '\n')
2646
2624
 
2647
2625
 
2712
2690
 
2713
2691
    _see_also = ['status', 'ignored', 'patterns']
2714
2692
    takes_args = ['name_pattern*']
2715
 
    takes_options = [
 
2693
    takes_options = ['directory',
2716
2694
        Option('default-rules',
2717
2695
               help='Display the default ignore rules that bzr uses.')
2718
2696
        ]
2719
2697
 
2720
 
    def run(self, name_pattern_list=None, default_rules=None):
 
2698
    def run(self, name_pattern_list=None, default_rules=None,
 
2699
            directory=u'.'):
2721
2700
        from bzrlib import ignores
2722
2701
        if default_rules is not None:
2723
2702
            # dump the default rules and exit
2734
2713
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2735
2714
                raise errors.BzrCommandError(
2736
2715
                    "NAME_PATTERN should not be an absolute path")
2737
 
        tree, relpath = WorkingTree.open_containing(u'.')
 
2716
        tree, relpath = WorkingTree.open_containing(directory)
2738
2717
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2739
2718
        ignored = globbing.Globster(name_pattern_list)
2740
2719
        matches = []
2766
2745
 
2767
2746
    encoding_type = 'replace'
2768
2747
    _see_also = ['ignore', 'ls']
 
2748
    takes_options = ['directory']
2769
2749
 
2770
2750
    @display_command
2771
 
    def run(self):
2772
 
        tree = WorkingTree.open_containing(u'.')[0]
2773
 
        tree.lock_read()
2774
 
        self.add_cleanup(tree.unlock)
 
2751
    def run(self, directory=u'.'):
 
2752
        tree = WorkingTree.open_containing(directory)[0]
 
2753
        self.add_cleanup(tree.lock_read().unlock)
2775
2754
        for path, file_class, kind, file_id, entry in tree.list_files():
2776
2755
            if file_class != 'I':
2777
2756
                continue
2788
2767
    """
2789
2768
    hidden = True
2790
2769
    takes_args = ['revno']
 
2770
    takes_options = ['directory']
2791
2771
 
2792
2772
    @display_command
2793
 
    def run(self, revno):
 
2773
    def run(self, revno, directory=u'.'):
2794
2774
        try:
2795
2775
            revno = int(revno)
2796
2776
        except ValueError:
2797
2777
            raise errors.BzrCommandError("not a valid revision-number: %r"
2798
2778
                                         % revno)
2799
 
        revid = WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
2779
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2800
2780
        self.outf.write("%s\n" % revid)
2801
2781
 
2802
2782
 
2829
2809
      =================       =========================
2830
2810
    """
2831
2811
    takes_args = ['dest', 'branch_or_subdir?']
2832
 
    takes_options = [
 
2812
    takes_options = ['directory',
2833
2813
        Option('format',
2834
2814
               help="Type of file to export to.",
2835
2815
               type=unicode),
2844
2824
                    'revision in which it was changed.'),
2845
2825
        ]
2846
2826
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2847
 
        root=None, filters=False, per_file_timestamps=False):
 
2827
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2848
2828
        from bzrlib.export import export
2849
2829
 
2850
2830
        if branch_or_subdir is None:
2851
 
            tree = WorkingTree.open_containing(u'.')[0]
 
2831
            tree = WorkingTree.open_containing(directory)[0]
2852
2832
            b = tree.branch
2853
2833
            subdir = None
2854
2834
        else:
2873
2853
    """
2874
2854
 
2875
2855
    _see_also = ['ls']
2876
 
    takes_options = [
 
2856
    takes_options = ['directory',
2877
2857
        Option('name-from-revision', help='The path name in the old tree.'),
2878
2858
        Option('filters', help='Apply content filters to display the '
2879
2859
                'convenience form.'),
2884
2864
 
2885
2865
    @display_command
2886
2866
    def run(self, filename, revision=None, name_from_revision=False,
2887
 
            filters=False):
 
2867
            filters=False, directory=None):
2888
2868
        if revision is not None and len(revision) != 1:
2889
2869
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2890
2870
                                         " one revision specifier")
2891
2871
        tree, branch, relpath = \
2892
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2893
 
        branch.lock_read()
2894
 
        self.add_cleanup(branch.unlock)
 
2872
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
2873
        self.add_cleanup(branch.lock_read().unlock)
2895
2874
        return self._run(tree, branch, relpath, filename, revision,
2896
2875
                         name_from_revision, filters)
2897
2876
 
2900
2879
        if tree is None:
2901
2880
            tree = b.basis_tree()
2902
2881
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2903
 
        rev_tree.lock_read()
2904
 
        self.add_cleanup(rev_tree.unlock)
 
2882
        self.add_cleanup(rev_tree.lock_read().unlock)
2905
2883
 
2906
2884
        old_file_id = rev_tree.path2id(relpath)
2907
2885
 
3169
3147
        def get_message(commit_obj):
3170
3148
            """Callback to get commit message"""
3171
3149
            if file:
3172
 
                my_message = codecs.open(
3173
 
                    file, 'rt', osutils.get_user_encoding()).read()
 
3150
                f = codecs.open(file, 'rt', osutils.get_user_encoding())
 
3151
                try:
 
3152
                    my_message = f.read()
 
3153
                finally:
 
3154
                    f.close()
3174
3155
            elif message is not None:
3175
3156
                my_message = message
3176
3157
            else:
3330
3311
 
3331
3312
            bzr whoami "Frank Chu <fchu@example.com>"
3332
3313
    """
3333
 
    takes_options = [ Option('email',
 
3314
    takes_options = [ 'directory',
 
3315
                      Option('email',
3334
3316
                             help='Display email address only.'),
3335
3317
                      Option('branch',
3336
3318
                             help='Set identity for the current branch instead of '
3340
3322
    encoding_type = 'replace'
3341
3323
 
3342
3324
    @display_command
3343
 
    def run(self, email=False, branch=False, name=None):
 
3325
    def run(self, email=False, branch=False, name=None, directory=None):
3344
3326
        if name is None:
3345
 
            # use branch if we're inside one; otherwise global config
3346
 
            try:
3347
 
                c = Branch.open_containing('.')[0].get_config()
3348
 
            except errors.NotBranchError:
3349
 
                c = config.GlobalConfig()
 
3327
            if directory is None:
 
3328
                # use branch if we're inside one; otherwise global config
 
3329
                try:
 
3330
                    c = Branch.open_containing(u'.')[0].get_config()
 
3331
                except errors.NotBranchError:
 
3332
                    c = config.GlobalConfig()
 
3333
            else:
 
3334
                c = Branch.open(directory).get_config()
3350
3335
            if email:
3351
3336
                self.outf.write(c.user_email() + '\n')
3352
3337
            else:
3362
3347
 
3363
3348
        # use global config unless --branch given
3364
3349
        if branch:
3365
 
            c = Branch.open_containing('.')[0].get_config()
 
3350
            if directory is None:
 
3351
                c = Branch.open_containing(u'.')[0].get_config()
 
3352
            else:
 
3353
                c = Branch.open(directory).get_config()
3366
3354
        else:
3367
3355
            c = config.GlobalConfig()
3368
3356
        c.set_user_option('email', name)
3380
3368
 
3381
3369
    _see_also = ['info']
3382
3370
    takes_args = ['nickname?']
3383
 
    def run(self, nickname=None):
3384
 
        branch = Branch.open_containing(u'.')[0]
 
3371
    takes_options = ['directory']
 
3372
    def run(self, nickname=None, directory=u'.'):
 
3373
        branch = Branch.open_containing(directory)[0]
3385
3374
        if nickname is None:
3386
3375
            self.printme(branch)
3387
3376
        else:
3612
3601
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3613
3602
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3614
3603
            # stdout, which would corrupt the subunit stream. 
3615
 
            if sys.platform == "win32" and sys.stdout.fileno() >= 0:
 
3604
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
3605
            # following code can be deleted when it's sufficiently deployed
 
3606
            # -- vila/mgz 20100514
 
3607
            if (sys.platform == "win32"
 
3608
                and getattr(sys.stdout, 'fileno', None) is not None):
3616
3609
                import msvcrt
3617
3610
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3618
3611
        if parallel:
3690
3683
 
3691
3684
        branch1 = Branch.open_containing(branch)[0]
3692
3685
        branch2 = Branch.open_containing(other)[0]
3693
 
        branch1.lock_read()
3694
 
        self.add_cleanup(branch1.unlock)
3695
 
        branch2.lock_read()
3696
 
        self.add_cleanup(branch2.unlock)
 
3686
        self.add_cleanup(branch1.lock_read().unlock)
 
3687
        self.add_cleanup(branch2.lock_read().unlock)
3697
3688
        last1 = ensure_null(branch1.last_revision())
3698
3689
        last2 = ensure_null(branch2.last_revision())
3699
3690
 
3793
3784
                ' completely merged into the source, pull from the'
3794
3785
                ' source rather than merging.  When this happens,'
3795
3786
                ' you do not need to commit the result.'),
3796
 
        Option('directory',
 
3787
        custom_help('directory',
3797
3788
               help='Branch to merge into, '
3798
 
                    'rather than the one containing the working directory.',
3799
 
               short_name='d',
3800
 
               type=unicode,
3801
 
               ),
 
3789
                    'rather than the one containing the working directory.'),
3802
3790
        Option('preview', help='Instead of merging, show a diff of the'
3803
3791
               ' merge.'),
3804
3792
        Option('interactive', help='Select changes interactively.',
3837
3825
            unversioned_filter=tree.is_ignored, view_info=view_info)
3838
3826
        pb = ui.ui_factory.nested_progress_bar()
3839
3827
        self.add_cleanup(pb.finished)
3840
 
        tree.lock_write()
3841
 
        self.add_cleanup(tree.unlock)
 
3828
        self.add_cleanup(tree.lock_write().unlock)
3842
3829
        if location is not None:
3843
3830
            try:
3844
3831
                mergeable = bundle.read_mergeable_from_url(location,
4100
4087
        if merge_type is None:
4101
4088
            merge_type = _mod_merge.Merge3Merger
4102
4089
        tree, file_list = tree_files(file_list)
4103
 
        tree.lock_write()
4104
 
        self.add_cleanup(tree.unlock)
 
4090
        self.add_cleanup(tree.lock_write().unlock)
4105
4091
        parents = tree.get_parent_ids()
4106
4092
        if len(parents) != 2:
4107
4093
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4217
4203
    def run(self, revision=None, no_backup=False, file_list=None,
4218
4204
            forget_merges=None):
4219
4205
        tree, file_list = tree_files(file_list)
4220
 
        tree.lock_tree_write()
4221
 
        self.add_cleanup(tree.unlock)
 
4206
        self.add_cleanup(tree.lock_tree_write().unlock)
4222
4207
        if forget_merges:
4223
4208
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4224
4209
        else:
4313
4298
    _see_also = ['merge', 'pull']
4314
4299
    takes_args = ['other_branch?']
4315
4300
    takes_options = [
 
4301
        'directory',
4316
4302
        Option('reverse', 'Reverse the order of revisions.'),
4317
4303
        Option('mine-only',
4318
4304
               'Display changes in the local branch only.'),
4340
4326
            theirs_only=False,
4341
4327
            log_format=None, long=False, short=False, line=False,
4342
4328
            show_ids=False, verbose=False, this=False, other=False,
4343
 
            include_merges=False, revision=None, my_revision=None):
 
4329
            include_merges=False, revision=None, my_revision=None,
 
4330
            directory=u'.'):
4344
4331
        from bzrlib.missing import find_unmerged, iter_log_revisions
4345
4332
        def message(s):
4346
4333
            if not is_quiet():
4359
4346
        elif theirs_only:
4360
4347
            restrict = 'remote'
4361
4348
 
4362
 
        local_branch = Branch.open_containing(u".")[0]
4363
 
        local_branch.lock_read()
4364
 
        self.add_cleanup(local_branch.unlock)
 
4349
        local_branch = Branch.open_containing(directory)[0]
 
4350
        self.add_cleanup(local_branch.lock_read().unlock)
4365
4351
 
4366
4352
        parent = local_branch.get_parent()
4367
4353
        if other_branch is None:
4378
4364
        if remote_branch.base == local_branch.base:
4379
4365
            remote_branch = local_branch
4380
4366
        else:
4381
 
            remote_branch.lock_read()
4382
 
            self.add_cleanup(remote_branch.unlock)
 
4367
            self.add_cleanup(remote_branch.lock_read().unlock)
4383
4368
 
4384
4369
        local_revid_range = _revision_range_to_revid_range(
4385
4370
            _get_revision_range(my_revision, local_branch,
4440
4425
            message("Branches are up to date.\n")
4441
4426
        self.cleanup_now()
4442
4427
        if not status_code and parent is None and other_branch is not None:
4443
 
            local_branch.lock_write()
4444
 
            self.add_cleanup(local_branch.unlock)
 
4428
            self.add_cleanup(local_branch.lock_write().unlock)
4445
4429
            # handle race conditions - a parent might be set while we run.
4446
4430
            if local_branch.get_parent() is None:
4447
4431
                local_branch.set_parent(remote_branch.base)
4547
4531
            b = Branch.open_containing(branch)[0]
4548
4532
        else:
4549
4533
            b = Branch.open(branch)
4550
 
        b.lock_read()
4551
 
        self.add_cleanup(b.unlock)
 
4534
        self.add_cleanup(b.lock_read().unlock)
4552
4535
        if revision is None:
4553
4536
            rev_id = b.last_revision()
4554
4537
        else:
4578
4561
                     Option('long', help='Show commit date in annotations.'),
4579
4562
                     'revision',
4580
4563
                     'show-ids',
 
4564
                     'directory',
4581
4565
                     ]
4582
4566
    encoding_type = 'exact'
4583
4567
 
4584
4568
    @display_command
4585
4569
    def run(self, filename, all=False, long=False, revision=None,
4586
 
            show_ids=False):
 
4570
            show_ids=False, directory=None):
4587
4571
        from bzrlib.annotate import annotate_file, annotate_file_tree
4588
4572
        wt, branch, relpath = \
4589
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
4573
            _open_directory_or_containing_tree_or_branch(filename, directory)
4590
4574
        if wt is not None:
4591
 
            wt.lock_read()
4592
 
            self.add_cleanup(wt.unlock)
 
4575
            self.add_cleanup(wt.lock_read().unlock)
4593
4576
        else:
4594
 
            branch.lock_read()
4595
 
            self.add_cleanup(branch.unlock)
 
4577
            self.add_cleanup(branch.lock_read().unlock)
4596
4578
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
4597
 
        tree.lock_read()
4598
 
        self.add_cleanup(tree.unlock)
 
4579
        self.add_cleanup(tree.lock_read().unlock)
4599
4580
        if wt is not None:
4600
4581
            file_id = wt.path2id(relpath)
4601
4582
        else:
4619
4600
 
4620
4601
    hidden = True # is this right ?
4621
4602
    takes_args = ['revision_id*']
4622
 
    takes_options = ['revision']
 
4603
    takes_options = ['directory', 'revision']
4623
4604
 
4624
 
    def run(self, revision_id_list=None, revision=None):
 
4605
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
4625
4606
        if revision_id_list is not None and revision is not None:
4626
4607
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4627
4608
        if revision_id_list is None and revision is None:
4628
4609
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4629
 
        b = WorkingTree.open_containing(u'.')[0].branch
4630
 
        b.lock_write()
4631
 
        self.add_cleanup(b.unlock)
 
4610
        b = WorkingTree.open_containing(directory)[0].branch
 
4611
        self.add_cleanup(b.lock_write().unlock)
4632
4612
        return self._run(b, revision_id_list, revision)
4633
4613
 
4634
4614
    def _run(self, b, revision_id_list, revision):
4693
4673
 
4694
4674
    _see_also = ['checkouts', 'unbind']
4695
4675
    takes_args = ['location?']
4696
 
    takes_options = []
 
4676
    takes_options = ['directory']
4697
4677
 
4698
 
    def run(self, location=None):
4699
 
        b, relpath = Branch.open_containing(u'.')
 
4678
    def run(self, location=None, directory=u'.'):
 
4679
        b, relpath = Branch.open_containing(directory)
4700
4680
        if location is None:
4701
4681
            try:
4702
4682
                location = b.get_old_bound_location()
4729
4709
 
4730
4710
    _see_also = ['checkouts', 'bind']
4731
4711
    takes_args = []
4732
 
    takes_options = []
 
4712
    takes_options = ['directory']
4733
4713
 
4734
 
    def run(self):
4735
 
        b, relpath = Branch.open_containing(u'.')
 
4714
    def run(self, directory=u'.'):
 
4715
        b, relpath = Branch.open_containing(directory)
4736
4716
        if not b.unbind():
4737
4717
            raise errors.BzrCommandError('Local branch is not bound')
4738
4718
 
4784
4764
            b = control.open_branch()
4785
4765
 
4786
4766
        if tree is not None:
4787
 
            tree.lock_write()
4788
 
            self.add_cleanup(tree.unlock)
 
4767
            self.add_cleanup(tree.lock_write().unlock)
4789
4768
        else:
4790
 
            b.lock_write()
4791
 
            self.add_cleanup(b.unlock)
 
4769
            self.add_cleanup(b.lock_write().unlock)
4792
4770
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4793
4771
 
4794
4772
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4902
4880
                    'result in a dynamically allocated port.  The default port '
4903
4881
                    'depends on the protocol.',
4904
4882
               type=str),
4905
 
        Option('directory',
4906
 
               help='Serve contents of this directory.',
4907
 
               type=unicode),
 
4883
        custom_help('directory',
 
4884
               help='Serve contents of this directory.'),
4908
4885
        Option('allow-writes',
4909
4886
               help='By default the server is a readonly server.  Supplying '
4910
4887
                    '--allow-writes enables write access to the contents of '
5046
5023
    _see_also = ['send']
5047
5024
 
5048
5025
    takes_options = [
 
5026
        'directory',
5049
5027
        RegistryOption.from_kwargs('patch-type',
5050
5028
            'The type of patch to include in the directive.',
5051
5029
            title='Patch type',
5064
5042
    encoding_type = 'exact'
5065
5043
 
5066
5044
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5067
 
            sign=False, revision=None, mail_to=None, message=None):
 
5045
            sign=False, revision=None, mail_to=None, message=None,
 
5046
            directory=u'.'):
5068
5047
        from bzrlib.revision import ensure_null, NULL_REVISION
5069
5048
        include_patch, include_bundle = {
5070
5049
            'plain': (False, False),
5071
5050
            'diff': (True, False),
5072
5051
            'bundle': (True, True),
5073
5052
            }[patch_type]
5074
 
        branch = Branch.open('.')
 
5053
        branch = Branch.open(directory)
5075
5054
        stored_submit_branch = branch.get_submit_branch()
5076
5055
        if submit_branch is None:
5077
5056
            submit_branch = stored_submit_branch
5162
5141
    given, in which case it is sent to a file.
5163
5142
 
5164
5143
    Mail is sent using your preferred mail program.  This should be transparent
5165
 
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
5144
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
5166
5145
    If the preferred client can't be found (or used), your editor will be used.
5167
5146
 
5168
5147
    To use a specific mail program, set the mail_client configuration option.
5339
5318
        Option('delete',
5340
5319
            help='Delete this tag rather than placing it.',
5341
5320
            ),
5342
 
        Option('directory',
5343
 
            help='Branch in which to place the tag.',
5344
 
            short_name='d',
5345
 
            type=unicode,
5346
 
            ),
 
5321
        custom_help('directory',
 
5322
            help='Branch in which to place the tag.'),
5347
5323
        Option('force',
5348
5324
            help='Replace existing tags.',
5349
5325
            ),
5357
5333
            revision=None,
5358
5334
            ):
5359
5335
        branch, relpath = Branch.open_containing(directory)
5360
 
        branch.lock_write()
5361
 
        self.add_cleanup(branch.unlock)
 
5336
        self.add_cleanup(branch.lock_write().unlock)
5362
5337
        if delete:
5363
5338
            if tag_name is None:
5364
5339
                raise errors.BzrCommandError("No tag specified to delete.")
5392
5367
 
5393
5368
    _see_also = ['tag']
5394
5369
    takes_options = [
5395
 
        Option('directory',
5396
 
            help='Branch whose tags should be displayed.',
5397
 
            short_name='d',
5398
 
            type=unicode,
5399
 
            ),
 
5370
        custom_help('directory',
 
5371
            help='Branch whose tags should be displayed.'),
5400
5372
        RegistryOption.from_kwargs('sort',
5401
5373
            'Sort tags by different criteria.', title='Sorting',
5402
5374
            alpha='Sort tags lexicographically (default).',
5419
5391
        if not tags:
5420
5392
            return
5421
5393
 
5422
 
        branch.lock_read()
5423
 
        self.add_cleanup(branch.unlock)
 
5394
        self.add_cleanup(branch.lock_read().unlock)
5424
5395
        if revision:
5425
5396
            graph = branch.repository.get_graph()
5426
5397
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
5573
5544
    """
5574
5545
 
5575
5546
    takes_args = ['to_location?']
5576
 
    takes_options = [Option('force',
 
5547
    takes_options = ['directory',
 
5548
                     Option('force',
5577
5549
                        help='Switch even if local commits will be lost.'),
5578
5550
                     'revision',
5579
5551
                     Option('create-branch', short_name='b',
5582
5554
                    ]
5583
5555
 
5584
5556
    def run(self, to_location=None, force=False, create_branch=False,
5585
 
            revision=None):
 
5557
            revision=None, directory=u'.'):
5586
5558
        from bzrlib import switch
5587
 
        tree_location = '.'
 
5559
        tree_location = directory
5588
5560
        revision = _get_one_revision('switch', revision)
5589
5561
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5590
5562
        if to_location is None:
5591
5563
            if revision is None:
5592
5564
                raise errors.BzrCommandError('You must supply either a'
5593
5565
                                             ' revision or a location')
5594
 
            to_location = '.'
 
5566
            to_location = tree_location
5595
5567
        try:
5596
5568
            branch = control_dir.open_branch()
5597
5569
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5872
5844
    takes_args = ['file*']
5873
5845
 
5874
5846
    takes_options = [
 
5847
        'directory',
5875
5848
        'revision',
5876
5849
        Option('all', help='Shelve all changes.'),
5877
5850
        'message',
5886
5859
    _see_also = ['unshelve']
5887
5860
 
5888
5861
    def run(self, revision=None, all=False, file_list=None, message=None,
5889
 
            writer=None, list=False, destroy=False):
 
5862
            writer=None, list=False, destroy=False, directory=u'.'):
5890
5863
        if list:
5891
5864
            return self.run_for_list()
5892
5865
        from bzrlib.shelf_ui import Shelver
5894
5867
            writer = bzrlib.option.diff_writer_registry.get()
5895
5868
        try:
5896
5869
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5897
 
                file_list, message, destroy=destroy)
 
5870
                file_list, message, destroy=destroy, directory=directory)
5898
5871
            try:
5899
5872
                shelver.run()
5900
5873
            finally:
5904
5877
 
5905
5878
    def run_for_list(self):
5906
5879
        tree = WorkingTree.open_containing('.')[0]
5907
 
        tree.lock_read()
5908
 
        self.add_cleanup(tree.unlock)
 
5880
        self.add_cleanup(tree.lock_read().unlock)
5909
5881
        manager = tree.get_shelf_manager()
5910
5882
        shelves = manager.active_shelves()
5911
5883
        if len(shelves) == 0:
5929
5901
 
5930
5902
    takes_args = ['shelf_id?']
5931
5903
    takes_options = [
 
5904
        'directory',
5932
5905
        RegistryOption.from_kwargs(
5933
5906
            'action', help="The action to perform.",
5934
5907
            enum_switch=False, value_switches=True,
5942
5915
    ]
5943
5916
    _see_also = ['shelve']
5944
5917
 
5945
 
    def run(self, shelf_id=None, action='apply'):
 
5918
    def run(self, shelf_id=None, action='apply', directory=u'.'):
5946
5919
        from bzrlib.shelf_ui import Unshelver
5947
 
        unshelver = Unshelver.from_args(shelf_id, action)
 
5920
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5948
5921
        try:
5949
5922
            unshelver.run()
5950
5923
        finally:
5966
5939
 
5967
5940
    To check what clean-tree will do, use --dry-run.
5968
5941
    """
5969
 
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5942
    takes_options = ['directory',
 
5943
                     Option('ignored', help='Delete all ignored files.'),
5970
5944
                     Option('detritus', help='Delete conflict files, merge'
5971
5945
                            ' backups, and failed selftest dirs.'),
5972
5946
                     Option('unknown',
5975
5949
                            ' deleting them.'),
5976
5950
                     Option('force', help='Do not prompt before deleting.')]
5977
5951
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5978
 
            force=False):
 
5952
            force=False, directory=u'.'):
5979
5953
        from bzrlib.clean_tree import clean_tree
5980
5954
        if not (unknown or ignored or detritus):
5981
5955
            unknown = True
5982
5956
        if dry_run:
5983
5957
            force = True
5984
 
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
5985
 
                   dry_run=dry_run, no_prompt=force)
 
5958
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
5959
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
5986
5960
 
5987
5961
 
5988
5962
class cmd_reference(Command):