~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Martin Pool
  • Date: 2010-07-16 15:49:06 UTC
  • mto: This revision was merged to the branch mainline in revision 5351.
  • Revision ID: mbp@canonical.com-20100716154906-m2xqq6nsu52tvowi
Deprecate and avoid internal_tree_files and tree_files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
75
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
76
76
 
77
77
 
 
78
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
78
79
def tree_files(file_list, default_branch=u'.', canonicalize=True,
79
80
    apply_view=True):
80
 
    try:
81
 
        return internal_tree_files(file_list, default_branch, canonicalize,
82
 
            apply_view)
83
 
    except errors.FileInWrongBranch, e:
84
 
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
85
 
                                     (e.path, file_list[0]))
 
81
    return internal_tree_files(file_list, default_branch, canonicalize,
 
82
        apply_view)
86
83
 
87
84
 
88
85
def tree_files_for_add(file_list):
152
149
 
153
150
# XXX: Bad function name; should possibly also be a class method of
154
151
# WorkingTree rather than a function.
 
152
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
155
153
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
156
154
    apply_view=True):
157
155
    """Convert command-line paths to a WorkingTree and relative paths.
158
156
 
 
157
    Deprecated: use WorkingTree.open_containing_paths instead.
 
158
 
159
159
    This is typically used for command-line processors that take one or
160
160
    more filenames, and infer the workingtree that contains them.
161
161
 
171
171
 
172
172
    :return: workingtree, [relative_paths]
173
173
    """
174
 
    if file_list is None or len(file_list) == 0:
175
 
        tree = WorkingTree.open_containing(default_branch)[0]
176
 
        if tree.supports_views() and apply_view:
177
 
            view_files = tree.views.lookup_view()
178
 
            if view_files:
179
 
                file_list = view_files
180
 
                view_str = views.view_display_str(view_files)
181
 
                note("Ignoring files outside view. View is %s" % view_str)
182
 
        return tree, file_list
183
 
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
184
 
    return tree, safe_relpath_files(tree, file_list, canonicalize,
185
 
        apply_view=apply_view)
186
 
 
187
 
 
188
 
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
189
 
    """Convert file_list into a list of relpaths in tree.
190
 
 
191
 
    :param tree: A tree to operate on.
192
 
    :param file_list: A list of user provided paths or None.
193
 
    :param apply_view: if True and a view is set, apply it or check that
194
 
        specified files are within it
195
 
    :return: A list of relative paths.
196
 
    :raises errors.PathNotChild: When a provided path is in a different tree
197
 
        than tree.
198
 
    """
199
 
    if file_list is None:
200
 
        return None
201
 
    if tree.supports_views() and apply_view:
202
 
        view_files = tree.views.lookup_view()
203
 
    else:
204
 
        view_files = []
205
 
    new_list = []
206
 
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
207
 
    # doesn't - fix that up here before we enter the loop.
208
 
    if canonicalize:
209
 
        fixer = lambda p: osutils.canonical_relpath(tree.basedir, p)
210
 
    else:
211
 
        fixer = tree.relpath
212
 
    for filename in file_list:
213
 
        try:
214
 
            relpath = fixer(osutils.dereference_path(filename))
215
 
            if  view_files and not osutils.is_inside_any(view_files, relpath):
216
 
                raise errors.FileOutsideView(filename, view_files)
217
 
            new_list.append(relpath)
218
 
        except errors.PathNotChild:
219
 
            raise errors.FileInWrongBranch(tree.branch, filename)
220
 
    return new_list
 
174
    return WorkingTree.open_containing_paths(
 
175
        file_list, default_directory='.',
 
176
        canonicalize=True,
 
177
        apply_view=True)
221
178
 
222
179
 
223
180
def _get_view_info_for_change_reporter(tree):
232
189
    return view_info
233
190
 
234
191
 
 
192
def _open_directory_or_containing_tree_or_branch(filename, directory):
 
193
    """Open the tree or branch containing the specified file, unless
 
194
    the --directory option is used to specify a different branch."""
 
195
    if directory is not None:
 
196
        return (None, Branch.open(directory), filename)
 
197
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
198
 
 
199
 
235
200
# TODO: Make sure no commands unconditionally use the working directory as a
236
201
# branch.  If a filename argument is used, the first of them should be used to
237
202
# specify the branch.  (Perhaps this can be factored out into some kind of
315
280
            raise errors.BzrCommandError('bzr status --revision takes exactly'
316
281
                                         ' one or two revision specifiers')
317
282
 
318
 
        tree, relfile_list = tree_files(file_list)
 
283
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
319
284
        # Avoid asking for specific files when that is not needed.
320
285
        if relfile_list == ['']:
321
286
            relfile_list = None
340
305
 
341
306
    hidden = True
342
307
    takes_args = ['revision_id?']
343
 
    takes_options = ['revision']
 
308
    takes_options = ['directory', 'revision']
344
309
    # cat-revision is more for frontends so should be exact
345
310
    encoding = 'strict'
346
311
 
353
318
        self.outf.write(revtext.decode('utf-8'))
354
319
 
355
320
    @display_command
356
 
    def run(self, revision_id=None, revision=None):
 
321
    def run(self, revision_id=None, revision=None, directory=u'.'):
357
322
        if revision_id is not None and revision is not None:
358
323
            raise errors.BzrCommandError('You can only supply one of'
359
324
                                         ' revision_id or --revision')
360
325
        if revision_id is None and revision is None:
361
326
            raise errors.BzrCommandError('You must supply either'
362
327
                                         ' --revision or a revision_id')
363
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
328
        b = WorkingTree.open_containing(directory)[0].branch
364
329
 
365
330
        revisions = b.repository.revisions
366
331
        if revisions is None:
483
448
    takes_options = [
484
449
        Option('force',
485
450
               help='Remove the working tree even if it has '
486
 
                    'uncommitted changes.'),
 
451
                    'uncommitted or shelved changes.'),
487
452
        ]
488
453
 
489
454
    def run(self, location_list, force=False):
503
468
            if not force:
504
469
                if (working.has_changes()):
505
470
                    raise errors.UncommittedChanges(working)
 
471
                if working.get_shelf_manager().last_shelf() is not None:
 
472
                    raise errors.ShelvedChanges(working)
506
473
 
507
474
            if working.user_url != working.branch.user_url:
508
475
                raise errors.BzrCommandError("You cannot remove the working tree"
552
519
    takes_args = ['revision_info*']
553
520
    takes_options = [
554
521
        'revision',
555
 
        Option('directory',
 
522
        custom_help('directory',
556
523
            help='Branch to examine, '
557
 
                 'rather than the one containing the working directory.',
558
 
            short_name='d',
559
 
            type=unicode,
560
 
            ),
 
524
                 'rather than the one containing the working directory.'),
561
525
        Option('tree', help='Show revno of working tree'),
562
526
        ]
563
527
 
754
718
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
755
719
 
756
720
        revision = _get_one_revision('inventory', revision)
757
 
        work_tree, file_list = tree_files(file_list)
 
721
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
758
722
        self.add_cleanup(work_tree.lock_read().unlock)
759
723
        if revision is not None:
760
724
            tree = revision.as_tree(work_tree.branch)
825
789
            names_list = []
826
790
        if len(names_list) < 2:
827
791
            raise errors.BzrCommandError("missing file argument")
828
 
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
792
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
829
793
        self.add_cleanup(tree.lock_tree_write().unlock)
830
794
        self._run(tree, names_list, rel_names, after)
831
795
 
836
800
        if after:
837
801
            raise errors.BzrCommandError('--after cannot be specified with'
838
802
                                         ' --auto.')
839
 
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
803
        work_tree, file_list = WorkingTree.open_containing_paths(
 
804
            names_list, default_branch='.')
840
805
        self.add_cleanup(work_tree.lock_tree_write().unlock)
841
806
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
842
807
 
951
916
    takes_options = ['remember', 'overwrite', 'revision',
952
917
        custom_help('verbose',
953
918
            help='Show logs of pulled revisions.'),
954
 
        Option('directory',
 
919
        custom_help('directory',
955
920
            help='Branch to pull into, '
956
 
                 'rather than the one containing the working directory.',
957
 
            short_name='d',
958
 
            type=unicode,
959
 
            ),
 
921
                 'rather than the one containing the working directory.'),
960
922
        Option('local',
961
923
            help="Perform a local pull in a bound "
962
924
                 "branch.  Local pulls are not applied to "
1076
1038
        Option('create-prefix',
1077
1039
               help='Create the path leading up to the branch '
1078
1040
                    'if it does not already exist.'),
1079
 
        Option('directory',
 
1041
        custom_help('directory',
1080
1042
            help='Branch to push from, '
1081
 
                 'rather than the one containing the working directory.',
1082
 
            short_name='d',
1083
 
            type=unicode,
1084
 
            ),
 
1043
                 'rather than the one containing the working directory.'),
1085
1044
        Option('use-existing-dir',
1086
1045
               help='By default push will fail if the target'
1087
1046
                    ' directory exists, but does not already'
1525
1484
 
1526
1485
    def run(self, file_list, verbose=False, new=False,
1527
1486
        file_deletion_strategy='safe'):
1528
 
        tree, file_list = tree_files(file_list)
 
1487
        tree, file_list = WorkingTree.open_containing_paths(file_list)
1529
1488
 
1530
1489
        if file_list is not None:
1531
1490
            file_list = [f for f in file_list]
1969
1928
         old_branch, new_branch,
1970
1929
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
1971
1930
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
 
1931
        # GNU diff on Windows uses ANSI encoding for filenames
 
1932
        path_encoding = osutils.get_diff_header_encoding()
1972
1933
        return show_diff_trees(old_tree, new_tree, sys.stdout,
1973
1934
                               specific_files=specific_files,
1974
1935
                               external_diff_options=diff_options,
1975
1936
                               old_label=old_label, new_label=new_label,
1976
 
                               extra_trees=extra_trees, using=using,
 
1937
                               extra_trees=extra_trees,
 
1938
                               path_encoding=path_encoding,
 
1939
                               using=using,
1977
1940
                               format_cls=format)
1978
1941
 
1979
1942
 
1987
1950
    # level of effort but possibly much less IO.  (Or possibly not,
1988
1951
    # if the directories are very large...)
1989
1952
    _see_also = ['status', 'ls']
1990
 
    takes_options = ['show-ids']
 
1953
    takes_options = ['directory', 'show-ids']
1991
1954
 
1992
1955
    @display_command
1993
 
    def run(self, show_ids=False):
1994
 
        tree = WorkingTree.open_containing(u'.')[0]
 
1956
    def run(self, show_ids=False, directory=u'.'):
 
1957
        tree = WorkingTree.open_containing(directory)[0]
1995
1958
        self.add_cleanup(tree.lock_read().unlock)
1996
1959
        old = tree.basis_tree()
1997
1960
        self.add_cleanup(old.lock_read().unlock)
2010
1973
 
2011
1974
    hidden = True
2012
1975
    _see_also = ['status', 'ls']
2013
 
    takes_options = [
2014
 
            Option('null',
2015
 
                   help='Write an ascii NUL (\\0) separator '
2016
 
                   'between files rather than a newline.')
2017
 
            ]
 
1976
    takes_options = ['directory', 'null']
2018
1977
 
2019
1978
    @display_command
2020
 
    def run(self, null=False):
2021
 
        tree = WorkingTree.open_containing(u'.')[0]
 
1979
    def run(self, null=False, directory=u'.'):
 
1980
        tree = WorkingTree.open_containing(directory)[0]
2022
1981
        td = tree.changes_from(tree.basis_tree())
2023
1982
        for path, id, kind, text_modified, meta_modified in td.modified:
2024
1983
            if null:
2033
1992
 
2034
1993
    hidden = True
2035
1994
    _see_also = ['status', 'ls']
2036
 
    takes_options = [
2037
 
            Option('null',
2038
 
                   help='Write an ascii NUL (\\0) separator '
2039
 
                   'between files rather than a newline.')
2040
 
            ]
 
1995
    takes_options = ['directory', 'null']
2041
1996
 
2042
1997
    @display_command
2043
 
    def run(self, null=False):
2044
 
        wt = WorkingTree.open_containing(u'.')[0]
 
1998
    def run(self, null=False, directory=u'.'):
 
1999
        wt = WorkingTree.open_containing(directory)[0]
2045
2000
        self.add_cleanup(wt.lock_read().unlock)
2046
2001
        basis = wt.basis_tree()
2047
2002
        self.add_cleanup(basis.lock_read().unlock)
2053
2008
            if inv.is_root(file_id) and len(basis_inv) == 0:
2054
2009
                continue
2055
2010
            path = inv.id2path(file_id)
2056
 
            if not os.access(osutils.abspath(path), os.F_OK):
 
2011
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2057
2012
                continue
2058
2013
            if null:
2059
2014
                self.outf.write(path + '\0')
2259
2214
                   help='Show just the specified revision.'
2260
2215
                   ' See also "help revisionspec".'),
2261
2216
            'log-format',
 
2217
            RegistryOption('authors',
 
2218
                'What names to list as authors - first, all or committer.',
 
2219
                title='Authors',
 
2220
                lazy_registry=('bzrlib.log', 'author_list_registry'),
 
2221
            ),
2262
2222
            Option('levels',
2263
2223
                   short_name='n',
2264
2224
                   help='Number of levels to display - 0 for all, 1 for flat.',
2299
2259
            limit=None,
2300
2260
            show_diff=False,
2301
2261
            include_merges=False,
 
2262
            authors=None,
2302
2263
            exclude_common_ancestry=False,
2303
2264
            ):
2304
2265
        from bzrlib.log import (
2382
2343
                        show_timezone=timezone,
2383
2344
                        delta_format=get_verbosity_level(),
2384
2345
                        levels=levels,
2385
 
                        show_advice=levels is None)
 
2346
                        show_advice=levels is None,
 
2347
                        author_list_handler=authors)
2386
2348
 
2387
2349
        # Choose the algorithm for doing the logging. It's annoying
2388
2350
        # having multiple code paths like this but necessary until
2505
2467
                   help='Recurse into subdirectories.'),
2506
2468
            Option('from-root',
2507
2469
                   help='Print paths relative to the root of the branch.'),
2508
 
            Option('unknown', help='Print unknown files.'),
 
2470
            Option('unknown', short_name='u',
 
2471
                help='Print unknown files.'),
2509
2472
            Option('versioned', help='Print versioned files.',
2510
2473
                   short_name='V'),
2511
 
            Option('ignored', help='Print ignored files.'),
2512
 
            Option('null',
2513
 
                   help='Write an ascii NUL (\\0) separator '
2514
 
                   'between files rather than a newline.'),
2515
 
            Option('kind',
 
2474
            Option('ignored', short_name='i',
 
2475
                help='Print ignored files.'),
 
2476
            Option('kind', short_name='k',
2516
2477
                   help='List entries of a particular kind: file, directory, symlink.',
2517
2478
                   type=unicode),
 
2479
            'null',
2518
2480
            'show-ids',
 
2481
            'directory',
2519
2482
            ]
2520
2483
    @display_command
2521
2484
    def run(self, revision=None, verbose=False,
2522
2485
            recursive=False, from_root=False,
2523
2486
            unknown=False, versioned=False, ignored=False,
2524
 
            null=False, kind=None, show_ids=False, path=None):
 
2487
            null=False, kind=None, show_ids=False, path=None, directory=None):
2525
2488
 
2526
2489
        if kind and kind not in ('file', 'directory', 'symlink'):
2527
2490
            raise errors.BzrCommandError('invalid kind specified')
2539
2502
                raise errors.BzrCommandError('cannot specify both --from-root'
2540
2503
                                             ' and PATH')
2541
2504
            fs_path = path
2542
 
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2543
 
            fs_path)
 
2505
        tree, branch, relpath = \
 
2506
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
2544
2507
 
2545
2508
        # Calculate the prefix to use
2546
2509
        prefix = None
2614
2577
 
2615
2578
    hidden = True
2616
2579
    _see_also = ['ls']
 
2580
    takes_options = ['directory']
2617
2581
 
2618
2582
    @display_command
2619
 
    def run(self):
2620
 
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
2583
    def run(self, directory=u'.'):
 
2584
        for f in WorkingTree.open_containing(directory)[0].unknowns():
2621
2585
            self.outf.write(osutils.quotefn(f) + '\n')
2622
2586
 
2623
2587
 
2688
2652
 
2689
2653
    _see_also = ['status', 'ignored', 'patterns']
2690
2654
    takes_args = ['name_pattern*']
2691
 
    takes_options = [
 
2655
    takes_options = ['directory',
2692
2656
        Option('default-rules',
2693
2657
               help='Display the default ignore rules that bzr uses.')
2694
2658
        ]
2695
2659
 
2696
 
    def run(self, name_pattern_list=None, default_rules=None):
 
2660
    def run(self, name_pattern_list=None, default_rules=None,
 
2661
            directory=u'.'):
2697
2662
        from bzrlib import ignores
2698
2663
        if default_rules is not None:
2699
2664
            # dump the default rules and exit
2710
2675
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2711
2676
                raise errors.BzrCommandError(
2712
2677
                    "NAME_PATTERN should not be an absolute path")
2713
 
        tree, relpath = WorkingTree.open_containing(u'.')
 
2678
        tree, relpath = WorkingTree.open_containing(directory)
2714
2679
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2715
2680
        ignored = globbing.Globster(name_pattern_list)
2716
2681
        matches = []
2717
 
        tree.lock_read()
 
2682
        self.add_cleanup(tree.lock_read().unlock)
2718
2683
        for entry in tree.list_files():
2719
2684
            id = entry[3]
2720
2685
            if id is not None:
2721
2686
                filename = entry[0]
2722
2687
                if ignored.match(filename):
2723
2688
                    matches.append(filename)
2724
 
        tree.unlock()
2725
2689
        if len(matches) > 0:
2726
2690
            self.outf.write("Warning: the following files are version controlled and"
2727
2691
                  " match your ignore pattern:\n%s"
2742
2706
 
2743
2707
    encoding_type = 'replace'
2744
2708
    _see_also = ['ignore', 'ls']
 
2709
    takes_options = ['directory']
2745
2710
 
2746
2711
    @display_command
2747
 
    def run(self):
2748
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2712
    def run(self, directory=u'.'):
 
2713
        tree = WorkingTree.open_containing(directory)[0]
2749
2714
        self.add_cleanup(tree.lock_read().unlock)
2750
2715
        for path, file_class, kind, file_id, entry in tree.list_files():
2751
2716
            if file_class != 'I':
2763
2728
    """
2764
2729
    hidden = True
2765
2730
    takes_args = ['revno']
 
2731
    takes_options = ['directory']
2766
2732
 
2767
2733
    @display_command
2768
 
    def run(self, revno):
 
2734
    def run(self, revno, directory=u'.'):
2769
2735
        try:
2770
2736
            revno = int(revno)
2771
2737
        except ValueError:
2772
2738
            raise errors.BzrCommandError("not a valid revision-number: %r"
2773
2739
                                         % revno)
2774
 
        revid = WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
2740
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2775
2741
        self.outf.write("%s\n" % revid)
2776
2742
 
2777
2743
 
2804
2770
      =================       =========================
2805
2771
    """
2806
2772
    takes_args = ['dest', 'branch_or_subdir?']
2807
 
    takes_options = [
 
2773
    takes_options = ['directory',
2808
2774
        Option('format',
2809
2775
               help="Type of file to export to.",
2810
2776
               type=unicode),
2819
2785
                    'revision in which it was changed.'),
2820
2786
        ]
2821
2787
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2822
 
        root=None, filters=False, per_file_timestamps=False):
 
2788
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2823
2789
        from bzrlib.export import export
2824
2790
 
2825
2791
        if branch_or_subdir is None:
2826
 
            tree = WorkingTree.open_containing(u'.')[0]
 
2792
            tree = WorkingTree.open_containing(directory)[0]
2827
2793
            b = tree.branch
2828
2794
            subdir = None
2829
2795
        else:
2848
2814
    """
2849
2815
 
2850
2816
    _see_also = ['ls']
2851
 
    takes_options = [
 
2817
    takes_options = ['directory',
2852
2818
        Option('name-from-revision', help='The path name in the old tree.'),
2853
2819
        Option('filters', help='Apply content filters to display the '
2854
2820
                'convenience form.'),
2859
2825
 
2860
2826
    @display_command
2861
2827
    def run(self, filename, revision=None, name_from_revision=False,
2862
 
            filters=False):
 
2828
            filters=False, directory=None):
2863
2829
        if revision is not None and len(revision) != 1:
2864
2830
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2865
2831
                                         " one revision specifier")
2866
2832
        tree, branch, relpath = \
2867
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2833
            _open_directory_or_containing_tree_or_branch(filename, directory)
2868
2834
        self.add_cleanup(branch.lock_read().unlock)
2869
2835
        return self._run(tree, branch, relpath, filename, revision,
2870
2836
                         name_from_revision, filters)
3101
3067
 
3102
3068
        properties = {}
3103
3069
 
3104
 
        tree, selected_list = tree_files(selected_list)
 
3070
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
3105
3071
        if selected_list == ['']:
3106
3072
            # workaround - commit of root of tree should be exactly the same
3107
3073
            # as just default commit in that tree, and succeed even though
3142
3108
        def get_message(commit_obj):
3143
3109
            """Callback to get commit message"""
3144
3110
            if file:
3145
 
                my_message = codecs.open(
3146
 
                    file, 'rt', osutils.get_user_encoding()).read()
 
3111
                f = codecs.open(file, 'rt', osutils.get_user_encoding())
 
3112
                try:
 
3113
                    my_message = f.read()
 
3114
                finally:
 
3115
                    f.close()
3147
3116
            elif message is not None:
3148
3117
                my_message = message
3149
3118
            else:
3178
3147
                        reporter=None, verbose=verbose, revprops=properties,
3179
3148
                        authors=author, timestamp=commit_stamp,
3180
3149
                        timezone=offset,
3181
 
                        exclude=safe_relpath_files(tree, exclude))
 
3150
                        exclude=tree.safe_relpath_files(exclude))
3182
3151
        except PointlessCommit:
3183
3152
            raise errors.BzrCommandError("No changes to commit."
3184
3153
                              " Use --unchanged to commit anyhow.")
3303
3272
 
3304
3273
            bzr whoami "Frank Chu <fchu@example.com>"
3305
3274
    """
3306
 
    takes_options = [ Option('email',
 
3275
    takes_options = [ 'directory',
 
3276
                      Option('email',
3307
3277
                             help='Display email address only.'),
3308
3278
                      Option('branch',
3309
3279
                             help='Set identity for the current branch instead of '
3313
3283
    encoding_type = 'replace'
3314
3284
 
3315
3285
    @display_command
3316
 
    def run(self, email=False, branch=False, name=None):
 
3286
    def run(self, email=False, branch=False, name=None, directory=None):
3317
3287
        if name is None:
3318
 
            # use branch if we're inside one; otherwise global config
3319
 
            try:
3320
 
                c = Branch.open_containing('.')[0].get_config()
3321
 
            except errors.NotBranchError:
3322
 
                c = config.GlobalConfig()
 
3288
            if directory is None:
 
3289
                # use branch if we're inside one; otherwise global config
 
3290
                try:
 
3291
                    c = Branch.open_containing(u'.')[0].get_config()
 
3292
                except errors.NotBranchError:
 
3293
                    c = config.GlobalConfig()
 
3294
            else:
 
3295
                c = Branch.open(directory).get_config()
3323
3296
            if email:
3324
3297
                self.outf.write(c.user_email() + '\n')
3325
3298
            else:
3335
3308
 
3336
3309
        # use global config unless --branch given
3337
3310
        if branch:
3338
 
            c = Branch.open_containing('.')[0].get_config()
 
3311
            if directory is None:
 
3312
                c = Branch.open_containing(u'.')[0].get_config()
 
3313
            else:
 
3314
                c = Branch.open(directory).get_config()
3339
3315
        else:
3340
3316
            c = config.GlobalConfig()
3341
3317
        c.set_user_option('email', name)
3353
3329
 
3354
3330
    _see_also = ['info']
3355
3331
    takes_args = ['nickname?']
3356
 
    def run(self, nickname=None):
3357
 
        branch = Branch.open_containing(u'.')[0]
 
3332
    takes_options = ['directory']
 
3333
    def run(self, nickname=None, directory=u'.'):
 
3334
        branch = Branch.open_containing(directory)[0]
3358
3335
        if nickname is None:
3359
3336
            self.printme(branch)
3360
3337
        else:
3585
3562
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3586
3563
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3587
3564
            # stdout, which would corrupt the subunit stream. 
3588
 
            if sys.platform == "win32" and sys.stdout.fileno() >= 0:
 
3565
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
3566
            # following code can be deleted when it's sufficiently deployed
 
3567
            # -- vila/mgz 20100514
 
3568
            if (sys.platform == "win32"
 
3569
                and getattr(sys.stdout, 'fileno', None) is not None):
3589
3570
                import msvcrt
3590
3571
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3591
3572
        if parallel:
3764
3745
                ' completely merged into the source, pull from the'
3765
3746
                ' source rather than merging.  When this happens,'
3766
3747
                ' you do not need to commit the result.'),
3767
 
        Option('directory',
 
3748
        custom_help('directory',
3768
3749
               help='Branch to merge into, '
3769
 
                    'rather than the one containing the working directory.',
3770
 
               short_name='d',
3771
 
               type=unicode,
3772
 
               ),
 
3750
                    'rather than the one containing the working directory.'),
3773
3751
        Option('preview', help='Instead of merging, show a diff of the'
3774
3752
               ' merge.'),
3775
3753
        Option('interactive', help='Select changes interactively.',
3875
3853
    def _do_preview(self, merger):
3876
3854
        from bzrlib.diff import show_diff_trees
3877
3855
        result_tree = self._get_preview(merger)
 
3856
        path_encoding = osutils.get_diff_header_encoding()
3878
3857
        show_diff_trees(merger.this_tree, result_tree, self.outf,
3879
 
                        old_label='', new_label='')
 
3858
                        old_label='', new_label='',
 
3859
                        path_encoding=path_encoding)
3880
3860
 
3881
3861
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3882
3862
        merger.change_reporter = change_reporter
4069
4049
        from bzrlib.conflicts import restore
4070
4050
        if merge_type is None:
4071
4051
            merge_type = _mod_merge.Merge3Merger
4072
 
        tree, file_list = tree_files(file_list)
 
4052
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4073
4053
        self.add_cleanup(tree.lock_write().unlock)
4074
4054
        parents = tree.get_parent_ids()
4075
4055
        if len(parents) != 2:
4185
4165
 
4186
4166
    def run(self, revision=None, no_backup=False, file_list=None,
4187
4167
            forget_merges=None):
4188
 
        tree, file_list = tree_files(file_list)
 
4168
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4189
4169
        self.add_cleanup(tree.lock_tree_write().unlock)
4190
4170
        if forget_merges:
4191
4171
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4281
4261
    _see_also = ['merge', 'pull']
4282
4262
    takes_args = ['other_branch?']
4283
4263
    takes_options = [
 
4264
        'directory',
4284
4265
        Option('reverse', 'Reverse the order of revisions.'),
4285
4266
        Option('mine-only',
4286
4267
               'Display changes in the local branch only.'),
4308
4289
            theirs_only=False,
4309
4290
            log_format=None, long=False, short=False, line=False,
4310
4291
            show_ids=False, verbose=False, this=False, other=False,
4311
 
            include_merges=False, revision=None, my_revision=None):
 
4292
            include_merges=False, revision=None, my_revision=None,
 
4293
            directory=u'.'):
4312
4294
        from bzrlib.missing import find_unmerged, iter_log_revisions
4313
4295
        def message(s):
4314
4296
            if not is_quiet():
4327
4309
        elif theirs_only:
4328
4310
            restrict = 'remote'
4329
4311
 
4330
 
        local_branch = Branch.open_containing(u".")[0]
 
4312
        local_branch = Branch.open_containing(directory)[0]
4331
4313
        self.add_cleanup(local_branch.lock_read().unlock)
4332
4314
 
4333
4315
        parent = local_branch.get_parent()
4542
4524
                     Option('long', help='Show commit date in annotations.'),
4543
4525
                     'revision',
4544
4526
                     'show-ids',
 
4527
                     'directory',
4545
4528
                     ]
4546
4529
    encoding_type = 'exact'
4547
4530
 
4548
4531
    @display_command
4549
4532
    def run(self, filename, all=False, long=False, revision=None,
4550
 
            show_ids=False):
 
4533
            show_ids=False, directory=None):
4551
4534
        from bzrlib.annotate import annotate_file, annotate_file_tree
4552
4535
        wt, branch, relpath = \
4553
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
4536
            _open_directory_or_containing_tree_or_branch(filename, directory)
4554
4537
        if wt is not None:
4555
4538
            self.add_cleanup(wt.lock_read().unlock)
4556
4539
        else:
4580
4563
 
4581
4564
    hidden = True # is this right ?
4582
4565
    takes_args = ['revision_id*']
4583
 
    takes_options = ['revision']
 
4566
    takes_options = ['directory', 'revision']
4584
4567
 
4585
 
    def run(self, revision_id_list=None, revision=None):
 
4568
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
4586
4569
        if revision_id_list is not None and revision is not None:
4587
4570
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4588
4571
        if revision_id_list is None and revision is None:
4589
4572
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4590
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
4573
        b = WorkingTree.open_containing(directory)[0].branch
4591
4574
        self.add_cleanup(b.lock_write().unlock)
4592
4575
        return self._run(b, revision_id_list, revision)
4593
4576
 
4653
4636
 
4654
4637
    _see_also = ['checkouts', 'unbind']
4655
4638
    takes_args = ['location?']
4656
 
    takes_options = []
 
4639
    takes_options = ['directory']
4657
4640
 
4658
 
    def run(self, location=None):
4659
 
        b, relpath = Branch.open_containing(u'.')
 
4641
    def run(self, location=None, directory=u'.'):
 
4642
        b, relpath = Branch.open_containing(directory)
4660
4643
        if location is None:
4661
4644
            try:
4662
4645
                location = b.get_old_bound_location()
4689
4672
 
4690
4673
    _see_also = ['checkouts', 'bind']
4691
4674
    takes_args = []
4692
 
    takes_options = []
 
4675
    takes_options = ['directory']
4693
4676
 
4694
 
    def run(self):
4695
 
        b, relpath = Branch.open_containing(u'.')
 
4677
    def run(self, directory=u'.'):
 
4678
        b, relpath = Branch.open_containing(directory)
4696
4679
        if not b.unbind():
4697
4680
            raise errors.BzrCommandError('Local branch is not bound')
4698
4681
 
4860
4843
                    'result in a dynamically allocated port.  The default port '
4861
4844
                    'depends on the protocol.',
4862
4845
               type=str),
4863
 
        Option('directory',
4864
 
               help='Serve contents of this directory.',
4865
 
               type=unicode),
 
4846
        custom_help('directory',
 
4847
               help='Serve contents of this directory.'),
4866
4848
        Option('allow-writes',
4867
4849
               help='By default the server is a readonly server.  Supplying '
4868
4850
                    '--allow-writes enables write access to the contents of '
4895
4877
 
4896
4878
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
4897
4879
            protocol=None):
4898
 
        from bzrlib.transport import get_transport, transport_server_registry
 
4880
        from bzrlib import transport
4899
4881
        if directory is None:
4900
4882
            directory = os.getcwd()
4901
4883
        if protocol is None:
4902
 
            protocol = transport_server_registry.get()
 
4884
            protocol = transport.transport_server_registry.get()
4903
4885
        host, port = self.get_host_and_port(port)
4904
4886
        url = urlutils.local_path_to_url(directory)
4905
4887
        if not allow_writes:
4906
4888
            url = 'readonly+' + url
4907
 
        transport = get_transport(url)
4908
 
        protocol(transport, host, port, inet)
 
4889
        t = transport.get_transport(url)
 
4890
        protocol(t, host, port, inet)
4909
4891
 
4910
4892
 
4911
4893
class cmd_join(Command):
5004
4986
    _see_also = ['send']
5005
4987
 
5006
4988
    takes_options = [
 
4989
        'directory',
5007
4990
        RegistryOption.from_kwargs('patch-type',
5008
4991
            'The type of patch to include in the directive.',
5009
4992
            title='Patch type',
5022
5005
    encoding_type = 'exact'
5023
5006
 
5024
5007
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5025
 
            sign=False, revision=None, mail_to=None, message=None):
 
5008
            sign=False, revision=None, mail_to=None, message=None,
 
5009
            directory=u'.'):
5026
5010
        from bzrlib.revision import ensure_null, NULL_REVISION
5027
5011
        include_patch, include_bundle = {
5028
5012
            'plain': (False, False),
5029
5013
            'diff': (True, False),
5030
5014
            'bundle': (True, True),
5031
5015
            }[patch_type]
5032
 
        branch = Branch.open('.')
 
5016
        branch = Branch.open(directory)
5033
5017
        stored_submit_branch = branch.get_submit_branch()
5034
5018
        if submit_branch is None:
5035
5019
            submit_branch = stored_submit_branch
5120
5104
    given, in which case it is sent to a file.
5121
5105
 
5122
5106
    Mail is sent using your preferred mail program.  This should be transparent
5123
 
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
5107
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
5124
5108
    If the preferred client can't be found (or used), your editor will be used.
5125
5109
 
5126
5110
    To use a specific mail program, set the mail_client configuration option.
5297
5281
        Option('delete',
5298
5282
            help='Delete this tag rather than placing it.',
5299
5283
            ),
5300
 
        Option('directory',
5301
 
            help='Branch in which to place the tag.',
5302
 
            short_name='d',
5303
 
            type=unicode,
5304
 
            ),
 
5284
        custom_help('directory',
 
5285
            help='Branch in which to place the tag.'),
5305
5286
        Option('force',
5306
5287
            help='Replace existing tags.',
5307
5288
            ),
5349
5330
 
5350
5331
    _see_also = ['tag']
5351
5332
    takes_options = [
5352
 
        Option('directory',
5353
 
            help='Branch whose tags should be displayed.',
5354
 
            short_name='d',
5355
 
            type=unicode,
5356
 
            ),
 
5333
        custom_help('directory',
 
5334
            help='Branch whose tags should be displayed.'),
5357
5335
        RegistryOption.from_kwargs('sort',
5358
5336
            'Sort tags by different criteria.', title='Sorting',
5359
5337
            alpha='Sort tags lexicographically (default).',
5529
5507
    """
5530
5508
 
5531
5509
    takes_args = ['to_location?']
5532
 
    takes_options = [Option('force',
 
5510
    takes_options = ['directory',
 
5511
                     Option('force',
5533
5512
                        help='Switch even if local commits will be lost.'),
5534
5513
                     'revision',
5535
5514
                     Option('create-branch', short_name='b',
5538
5517
                    ]
5539
5518
 
5540
5519
    def run(self, to_location=None, force=False, create_branch=False,
5541
 
            revision=None):
 
5520
            revision=None, directory=u'.'):
5542
5521
        from bzrlib import switch
5543
 
        tree_location = '.'
 
5522
        tree_location = directory
5544
5523
        revision = _get_one_revision('switch', revision)
5545
5524
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5546
5525
        if to_location is None:
5547
5526
            if revision is None:
5548
5527
                raise errors.BzrCommandError('You must supply either a'
5549
5528
                                             ' revision or a location')
5550
 
            to_location = '.'
 
5529
            to_location = tree_location
5551
5530
        try:
5552
5531
            branch = control_dir.open_branch()
5553
5532
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5688
5667
            name=None,
5689
5668
            switch=None,
5690
5669
            ):
5691
 
        tree, file_list = tree_files(file_list, apply_view=False)
 
5670
        tree, file_list = WorkingTree.open_containing_paths(file_list,
 
5671
            apply_view=False)
5692
5672
        current_view, view_dict = tree.views.get_view_info()
5693
5673
        if name is None:
5694
5674
            name = current_view
5828
5808
    takes_args = ['file*']
5829
5809
 
5830
5810
    takes_options = [
 
5811
        'directory',
5831
5812
        'revision',
5832
5813
        Option('all', help='Shelve all changes.'),
5833
5814
        'message',
5842
5823
    _see_also = ['unshelve']
5843
5824
 
5844
5825
    def run(self, revision=None, all=False, file_list=None, message=None,
5845
 
            writer=None, list=False, destroy=False):
 
5826
            writer=None, list=False, destroy=False, directory=u'.'):
5846
5827
        if list:
5847
5828
            return self.run_for_list()
5848
5829
        from bzrlib.shelf_ui import Shelver
5850
5831
            writer = bzrlib.option.diff_writer_registry.get()
5851
5832
        try:
5852
5833
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5853
 
                file_list, message, destroy=destroy)
 
5834
                file_list, message, destroy=destroy, directory=directory)
5854
5835
            try:
5855
5836
                shelver.run()
5856
5837
            finally:
5884
5865
 
5885
5866
    takes_args = ['shelf_id?']
5886
5867
    takes_options = [
 
5868
        'directory',
5887
5869
        RegistryOption.from_kwargs(
5888
5870
            'action', help="The action to perform.",
5889
5871
            enum_switch=False, value_switches=True,
5897
5879
    ]
5898
5880
    _see_also = ['shelve']
5899
5881
 
5900
 
    def run(self, shelf_id=None, action='apply'):
 
5882
    def run(self, shelf_id=None, action='apply', directory=u'.'):
5901
5883
        from bzrlib.shelf_ui import Unshelver
5902
 
        unshelver = Unshelver.from_args(shelf_id, action)
 
5884
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5903
5885
        try:
5904
5886
            unshelver.run()
5905
5887
        finally:
5921
5903
 
5922
5904
    To check what clean-tree will do, use --dry-run.
5923
5905
    """
5924
 
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5906
    takes_options = ['directory',
 
5907
                     Option('ignored', help='Delete all ignored files.'),
5925
5908
                     Option('detritus', help='Delete conflict files, merge'
5926
5909
                            ' backups, and failed selftest dirs.'),
5927
5910
                     Option('unknown',
5930
5913
                            ' deleting them.'),
5931
5914
                     Option('force', help='Do not prompt before deleting.')]
5932
5915
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5933
 
            force=False):
 
5916
            force=False, directory=u'.'):
5934
5917
        from bzrlib.clean_tree import clean_tree
5935
5918
        if not (unknown or ignored or detritus):
5936
5919
            unknown = True
5937
5920
        if dry_run:
5938
5921
            force = True
5939
 
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
5940
 
                   dry_run=dry_run, no_prompt=force)
 
5922
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
5923
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
5941
5924
 
5942
5925
 
5943
5926
class cmd_reference(Command):