~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: John Arbash Meinel
  • Date: 2010-09-01 18:43:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5405.
  • Revision ID: john@arbash-meinel.com-20100901184332-3j58dhqd3y66fz0q
Make the test run again.

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
23
 
import codecs
24
23
import cStringIO
25
24
import sys
26
25
import time
33
32
    bzrdir,
34
33
    directory_service,
35
34
    delta,
36
 
    config,
 
35
    config as _mod_config,
37
36
    errors,
38
37
    globbing,
39
38
    hooks,
75
74
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
76
75
 
77
76
 
 
77
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
78
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
79
79
    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]))
 
80
    return internal_tree_files(file_list, default_branch, canonicalize,
 
81
        apply_view)
86
82
 
87
83
 
88
84
def tree_files_for_add(file_list):
152
148
 
153
149
# XXX: Bad function name; should possibly also be a class method of
154
150
# WorkingTree rather than a function.
 
151
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
155
152
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
156
153
    apply_view=True):
157
154
    """Convert command-line paths to a WorkingTree and relative paths.
158
155
 
 
156
    Deprecated: use WorkingTree.open_containing_paths instead.
 
157
 
159
158
    This is typically used for command-line processors that take one or
160
159
    more filenames, and infer the workingtree that contains them.
161
160
 
171
170
 
172
171
    :return: workingtree, [relative_paths]
173
172
    """
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
 
173
    return WorkingTree.open_containing_paths(
 
174
        file_list, default_directory='.',
 
175
        canonicalize=True,
 
176
        apply_view=True)
221
177
 
222
178
 
223
179
def _get_view_info_for_change_reporter(tree):
232
188
    return view_info
233
189
 
234
190
 
 
191
def _open_directory_or_containing_tree_or_branch(filename, directory):
 
192
    """Open the tree or branch containing the specified file, unless
 
193
    the --directory option is used to specify a different branch."""
 
194
    if directory is not None:
 
195
        return (None, Branch.open(directory), filename)
 
196
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
197
 
 
198
 
235
199
# TODO: Make sure no commands unconditionally use the working directory as a
236
200
# branch.  If a filename argument is used, the first of them should be used to
237
201
# specify the branch.  (Perhaps this can be factored out into some kind of
315
279
            raise errors.BzrCommandError('bzr status --revision takes exactly'
316
280
                                         ' one or two revision specifiers')
317
281
 
318
 
        tree, relfile_list = tree_files(file_list)
 
282
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
319
283
        # Avoid asking for specific files when that is not needed.
320
284
        if relfile_list == ['']:
321
285
            relfile_list = None
340
304
 
341
305
    hidden = True
342
306
    takes_args = ['revision_id?']
343
 
    takes_options = ['revision']
 
307
    takes_options = ['directory', 'revision']
344
308
    # cat-revision is more for frontends so should be exact
345
309
    encoding = 'strict'
346
310
 
353
317
        self.outf.write(revtext.decode('utf-8'))
354
318
 
355
319
    @display_command
356
 
    def run(self, revision_id=None, revision=None):
 
320
    def run(self, revision_id=None, revision=None, directory=u'.'):
357
321
        if revision_id is not None and revision is not None:
358
322
            raise errors.BzrCommandError('You can only supply one of'
359
323
                                         ' revision_id or --revision')
360
324
        if revision_id is None and revision is None:
361
325
            raise errors.BzrCommandError('You must supply either'
362
326
                                         ' --revision or a revision_id')
363
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
327
        b = WorkingTree.open_containing(directory)[0].branch
364
328
 
365
329
        revisions = b.repository.revisions
366
330
        if revisions is None:
483
447
    takes_options = [
484
448
        Option('force',
485
449
               help='Remove the working tree even if it has '
486
 
                    'uncommitted changes.'),
 
450
                    'uncommitted or shelved changes.'),
487
451
        ]
488
452
 
489
453
    def run(self, location_list, force=False):
503
467
            if not force:
504
468
                if (working.has_changes()):
505
469
                    raise errors.UncommittedChanges(working)
 
470
                if working.get_shelf_manager().last_shelf() is not None:
 
471
                    raise errors.ShelvedChanges(working)
506
472
 
507
473
            if working.user_url != working.branch.user_url:
508
474
                raise errors.BzrCommandError("You cannot remove the working tree"
552
518
    takes_args = ['revision_info*']
553
519
    takes_options = [
554
520
        'revision',
555
 
        Option('directory',
 
521
        custom_help('directory',
556
522
            help='Branch to examine, '
557
 
                 'rather than the one containing the working directory.',
558
 
            short_name='d',
559
 
            type=unicode,
560
 
            ),
 
523
                 'rather than the one containing the working directory.'),
561
524
        Option('tree', help='Show revno of working tree'),
562
525
        ]
563
526
 
754
717
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
755
718
 
756
719
        revision = _get_one_revision('inventory', revision)
757
 
        work_tree, file_list = tree_files(file_list)
 
720
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
758
721
        self.add_cleanup(work_tree.lock_read().unlock)
759
722
        if revision is not None:
760
723
            tree = revision.as_tree(work_tree.branch)
825
788
            names_list = []
826
789
        if len(names_list) < 2:
827
790
            raise errors.BzrCommandError("missing file argument")
828
 
        tree, rel_names = tree_files(names_list, canonicalize=False)
 
791
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
829
792
        self.add_cleanup(tree.lock_tree_write().unlock)
830
793
        self._run(tree, names_list, rel_names, after)
831
794
 
836
799
        if after:
837
800
            raise errors.BzrCommandError('--after cannot be specified with'
838
801
                                         ' --auto.')
839
 
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
802
        work_tree, file_list = WorkingTree.open_containing_paths(
 
803
            names_list, default_directory='.')
840
804
        self.add_cleanup(work_tree.lock_tree_write().unlock)
841
805
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
842
806
 
951
915
    takes_options = ['remember', 'overwrite', 'revision',
952
916
        custom_help('verbose',
953
917
            help='Show logs of pulled revisions.'),
954
 
        Option('directory',
 
918
        custom_help('directory',
955
919
            help='Branch to pull into, '
956
 
                 'rather than the one containing the working directory.',
957
 
            short_name='d',
958
 
            type=unicode,
959
 
            ),
 
920
                 'rather than the one containing the working directory.'),
960
921
        Option('local',
961
922
            help="Perform a local pull in a bound "
962
923
                 "branch.  Local pulls are not applied to "
1076
1037
        Option('create-prefix',
1077
1038
               help='Create the path leading up to the branch '
1078
1039
                    'if it does not already exist.'),
1079
 
        Option('directory',
 
1040
        custom_help('directory',
1080
1041
            help='Branch to push from, '
1081
 
                 'rather than the one containing the working directory.',
1082
 
            short_name='d',
1083
 
            type=unicode,
1084
 
            ),
 
1042
                 'rather than the one containing the working directory.'),
1085
1043
        Option('use-existing-dir',
1086
1044
               help='By default push will fail if the target'
1087
1045
                    ' directory exists, but does not already'
1176
1134
 
1177
1135
    _see_also = ['checkout']
1178
1136
    takes_args = ['from_location', 'to_location?']
1179
 
    takes_options = ['revision', Option('hardlink',
1180
 
        help='Hard-link working tree files where possible.'),
 
1137
    takes_options = ['revision',
 
1138
        Option('hardlink', help='Hard-link working tree files where possible.'),
 
1139
        Option('files-from', type=str,
 
1140
               help="Get file contents from this tree."),
1181
1141
        Option('no-tree',
1182
1142
            help="Create a branch without a working-tree."),
1183
1143
        Option('switch',
1201
1161
 
1202
1162
    def run(self, from_location, to_location=None, revision=None,
1203
1163
            hardlink=False, stacked=False, standalone=False, no_tree=False,
1204
 
            use_existing_dir=False, switch=False, bind=False):
 
1164
            use_existing_dir=False, switch=False, bind=False,
 
1165
            files_from=None):
1205
1166
        from bzrlib import switch as _mod_switch
1206
1167
        from bzrlib.tag import _merge_tags_if_possible
1207
1168
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1208
1169
            from_location)
 
1170
        if not (hardlink or files_from):
 
1171
            # accelerator_tree is usually slower because you have to read N
 
1172
            # files (no readahead, lots of seeks, etc), but allow the user to
 
1173
            # explicitly request it
 
1174
            accelerator_tree = None
 
1175
        if files_from is not None and files_from != from_location:
 
1176
            accelerator_tree = WorkingTree.open(files_from)
1209
1177
        revision = _get_one_revision('branch', revision)
1210
1178
        self.add_cleanup(br_from.lock_read().unlock)
1211
1179
        if revision is not None:
1318
1286
            to_location = branch_location
1319
1287
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1320
1288
            branch_location)
 
1289
        if not (hardlink or files_from):
 
1290
            # accelerator_tree is usually slower because you have to read N
 
1291
            # files (no readahead, lots of seeks, etc), but allow the user to
 
1292
            # explicitly request it
 
1293
            accelerator_tree = None
1321
1294
        revision = _get_one_revision('checkout', revision)
1322
 
        if files_from is not None:
 
1295
        if files_from is not None and files_from != branch_location:
1323
1296
            accelerator_tree = WorkingTree.open(files_from)
1324
1297
        if revision is not None:
1325
1298
            revision_id = revision.as_revision_id(source)
1504
1477
class cmd_remove(Command):
1505
1478
    __doc__ = """Remove files or directories.
1506
1479
 
1507
 
    This makes bzr stop tracking changes to the specified files. bzr will delete
1508
 
    them if they can easily be recovered using revert. If no options or
1509
 
    parameters are given bzr will scan for files that are being tracked by bzr
1510
 
    but missing in your tree and stop tracking them for you.
 
1480
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
 
1481
    delete them if they can easily be recovered using revert otherwise they
 
1482
    will be backed up (adding an extention of the form .~#~). If no options or
 
1483
    parameters are given Bazaar will scan for files that are being tracked by
 
1484
    Bazaar but missing in your tree and stop tracking them for you.
1511
1485
    """
1512
1486
    takes_args = ['file*']
1513
1487
    takes_options = ['verbose',
1515
1489
        RegistryOption.from_kwargs('file-deletion-strategy',
1516
1490
            'The file deletion mode to be used.',
1517
1491
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1518
 
            safe='Only delete files if they can be'
1519
 
                 ' safely recovered (default).',
 
1492
            safe='Backup changed files (default).',
1520
1493
            keep='Delete from bzr but leave the working copy.',
1521
1494
            force='Delete all the specified files, even if they can not be '
1522
1495
                'recovered and even if they are non-empty directories.')]
1525
1498
 
1526
1499
    def run(self, file_list, verbose=False, new=False,
1527
1500
        file_deletion_strategy='safe'):
1528
 
        tree, file_list = tree_files(file_list)
 
1501
        tree, file_list = WorkingTree.open_containing_paths(file_list)
1529
1502
 
1530
1503
        if file_list is not None:
1531
1504
            file_list = [f for f in file_list]
1619
1592
 
1620
1593
    _see_also = ['check']
1621
1594
    takes_args = ['branch?']
 
1595
    takes_options = [
 
1596
        Option('canonicalize-chks',
 
1597
               help='Make sure CHKs are in canonical form (repairs '
 
1598
                    'bug 522637).',
 
1599
               hidden=True),
 
1600
        ]
1622
1601
 
1623
 
    def run(self, branch="."):
 
1602
    def run(self, branch=".", canonicalize_chks=False):
1624
1603
        from bzrlib.reconcile import reconcile
1625
1604
        dir = bzrdir.BzrDir.open(branch)
1626
 
        reconcile(dir)
 
1605
        reconcile(dir, canonicalize_chks=canonicalize_chks)
1627
1606
 
1628
1607
 
1629
1608
class cmd_revision_history(Command):
1905
1884
        Same as 'bzr diff' but prefix paths with old/ and new/::
1906
1885
 
1907
1886
            bzr diff --prefix old/:new/
 
1887
            
 
1888
        Show the differences using a custom diff program with options::
 
1889
        
 
1890
            bzr diff --using /usr/bin/diff --diff-options -wu
1908
1891
    """
1909
1892
    _see_also = ['status']
1910
1893
    takes_args = ['file*']
1969
1952
         old_branch, new_branch,
1970
1953
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
1971
1954
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
 
1955
        # GNU diff on Windows uses ANSI encoding for filenames
 
1956
        path_encoding = osutils.get_diff_header_encoding()
1972
1957
        return show_diff_trees(old_tree, new_tree, sys.stdout,
1973
1958
                               specific_files=specific_files,
1974
1959
                               external_diff_options=diff_options,
1975
1960
                               old_label=old_label, new_label=new_label,
1976
 
                               extra_trees=extra_trees, using=using,
 
1961
                               extra_trees=extra_trees,
 
1962
                               path_encoding=path_encoding,
 
1963
                               using=using,
1977
1964
                               format_cls=format)
1978
1965
 
1979
1966
 
1987
1974
    # level of effort but possibly much less IO.  (Or possibly not,
1988
1975
    # if the directories are very large...)
1989
1976
    _see_also = ['status', 'ls']
1990
 
    takes_options = ['show-ids']
 
1977
    takes_options = ['directory', 'show-ids']
1991
1978
 
1992
1979
    @display_command
1993
 
    def run(self, show_ids=False):
1994
 
        tree = WorkingTree.open_containing(u'.')[0]
 
1980
    def run(self, show_ids=False, directory=u'.'):
 
1981
        tree = WorkingTree.open_containing(directory)[0]
1995
1982
        self.add_cleanup(tree.lock_read().unlock)
1996
1983
        old = tree.basis_tree()
1997
1984
        self.add_cleanup(old.lock_read().unlock)
2010
1997
 
2011
1998
    hidden = True
2012
1999
    _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
 
            ]
 
2000
    takes_options = ['directory', 'null']
2018
2001
 
2019
2002
    @display_command
2020
 
    def run(self, null=False):
2021
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2003
    def run(self, null=False, directory=u'.'):
 
2004
        tree = WorkingTree.open_containing(directory)[0]
2022
2005
        td = tree.changes_from(tree.basis_tree())
2023
2006
        for path, id, kind, text_modified, meta_modified in td.modified:
2024
2007
            if null:
2033
2016
 
2034
2017
    hidden = True
2035
2018
    _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
 
            ]
 
2019
    takes_options = ['directory', 'null']
2041
2020
 
2042
2021
    @display_command
2043
 
    def run(self, null=False):
2044
 
        wt = WorkingTree.open_containing(u'.')[0]
 
2022
    def run(self, null=False, directory=u'.'):
 
2023
        wt = WorkingTree.open_containing(directory)[0]
2045
2024
        self.add_cleanup(wt.lock_read().unlock)
2046
2025
        basis = wt.basis_tree()
2047
2026
        self.add_cleanup(basis.lock_read().unlock)
2053
2032
            if inv.is_root(file_id) and len(basis_inv) == 0:
2054
2033
                continue
2055
2034
            path = inv.id2path(file_id)
2056
 
            if not os.access(osutils.abspath(path), os.F_OK):
 
2035
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2057
2036
                continue
2058
2037
            if null:
2059
2038
                self.outf.write(path + '\0')
2259
2238
                   help='Show just the specified revision.'
2260
2239
                   ' See also "help revisionspec".'),
2261
2240
            'log-format',
 
2241
            RegistryOption('authors',
 
2242
                'What names to list as authors - first, all or committer.',
 
2243
                title='Authors',
 
2244
                lazy_registry=('bzrlib.log', 'author_list_registry'),
 
2245
            ),
2262
2246
            Option('levels',
2263
2247
                   short_name='n',
2264
2248
                   help='Number of levels to display - 0 for all, 1 for flat.',
2299
2283
            limit=None,
2300
2284
            show_diff=False,
2301
2285
            include_merges=False,
 
2286
            authors=None,
2302
2287
            exclude_common_ancestry=False,
2303
2288
            ):
2304
2289
        from bzrlib.log import (
2382
2367
                        show_timezone=timezone,
2383
2368
                        delta_format=get_verbosity_level(),
2384
2369
                        levels=levels,
2385
 
                        show_advice=levels is None)
 
2370
                        show_advice=levels is None,
 
2371
                        author_list_handler=authors)
2386
2372
 
2387
2373
        # Choose the algorithm for doing the logging. It's annoying
2388
2374
        # having multiple code paths like this but necessary until
2505
2491
                   help='Recurse into subdirectories.'),
2506
2492
            Option('from-root',
2507
2493
                   help='Print paths relative to the root of the branch.'),
2508
 
            Option('unknown', help='Print unknown files.'),
 
2494
            Option('unknown', short_name='u',
 
2495
                help='Print unknown files.'),
2509
2496
            Option('versioned', help='Print versioned files.',
2510
2497
                   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',
 
2498
            Option('ignored', short_name='i',
 
2499
                help='Print ignored files.'),
 
2500
            Option('kind', short_name='k',
2516
2501
                   help='List entries of a particular kind: file, directory, symlink.',
2517
2502
                   type=unicode),
 
2503
            'null',
2518
2504
            'show-ids',
 
2505
            'directory',
2519
2506
            ]
2520
2507
    @display_command
2521
2508
    def run(self, revision=None, verbose=False,
2522
2509
            recursive=False, from_root=False,
2523
2510
            unknown=False, versioned=False, ignored=False,
2524
 
            null=False, kind=None, show_ids=False, path=None):
 
2511
            null=False, kind=None, show_ids=False, path=None, directory=None):
2525
2512
 
2526
2513
        if kind and kind not in ('file', 'directory', 'symlink'):
2527
2514
            raise errors.BzrCommandError('invalid kind specified')
2539
2526
                raise errors.BzrCommandError('cannot specify both --from-root'
2540
2527
                                             ' and PATH')
2541
2528
            fs_path = path
2542
 
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2543
 
            fs_path)
 
2529
        tree, branch, relpath = \
 
2530
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
2544
2531
 
2545
2532
        # Calculate the prefix to use
2546
2533
        prefix = None
2614
2601
 
2615
2602
    hidden = True
2616
2603
    _see_also = ['ls']
 
2604
    takes_options = ['directory']
2617
2605
 
2618
2606
    @display_command
2619
 
    def run(self):
2620
 
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
2607
    def run(self, directory=u'.'):
 
2608
        for f in WorkingTree.open_containing(directory)[0].unknowns():
2621
2609
            self.outf.write(osutils.quotefn(f) + '\n')
2622
2610
 
2623
2611
 
2688
2676
 
2689
2677
    _see_also = ['status', 'ignored', 'patterns']
2690
2678
    takes_args = ['name_pattern*']
2691
 
    takes_options = [
 
2679
    takes_options = ['directory',
2692
2680
        Option('default-rules',
2693
2681
               help='Display the default ignore rules that bzr uses.')
2694
2682
        ]
2695
2683
 
2696
 
    def run(self, name_pattern_list=None, default_rules=None):
 
2684
    def run(self, name_pattern_list=None, default_rules=None,
 
2685
            directory=u'.'):
2697
2686
        from bzrlib import ignores
2698
2687
        if default_rules is not None:
2699
2688
            # dump the default rules and exit
2705
2694
                "NAME_PATTERN or --default-rules.")
2706
2695
        name_pattern_list = [globbing.normalize_pattern(p)
2707
2696
                             for p in name_pattern_list]
 
2697
        bad_patterns = ''
 
2698
        for p in name_pattern_list:
 
2699
            if not globbing.Globster.is_pattern_valid(p):
 
2700
                bad_patterns += ('\n  %s' % p)
 
2701
        if bad_patterns:
 
2702
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
 
2703
            ui.ui_factory.show_error(msg)
 
2704
            raise errors.InvalidPattern('')
2708
2705
        for name_pattern in name_pattern_list:
2709
2706
            if (name_pattern[0] == '/' or
2710
2707
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2711
2708
                raise errors.BzrCommandError(
2712
2709
                    "NAME_PATTERN should not be an absolute path")
2713
 
        tree, relpath = WorkingTree.open_containing(u'.')
 
2710
        tree, relpath = WorkingTree.open_containing(directory)
2714
2711
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2715
2712
        ignored = globbing.Globster(name_pattern_list)
2716
2713
        matches = []
2717
 
        tree.lock_read()
 
2714
        self.add_cleanup(tree.lock_read().unlock)
2718
2715
        for entry in tree.list_files():
2719
2716
            id = entry[3]
2720
2717
            if id is not None:
2721
2718
                filename = entry[0]
2722
2719
                if ignored.match(filename):
2723
2720
                    matches.append(filename)
2724
 
        tree.unlock()
2725
2721
        if len(matches) > 0:
2726
2722
            self.outf.write("Warning: the following files are version controlled and"
2727
2723
                  " match your ignore pattern:\n%s"
2742
2738
 
2743
2739
    encoding_type = 'replace'
2744
2740
    _see_also = ['ignore', 'ls']
 
2741
    takes_options = ['directory']
2745
2742
 
2746
2743
    @display_command
2747
 
    def run(self):
2748
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2744
    def run(self, directory=u'.'):
 
2745
        tree = WorkingTree.open_containing(directory)[0]
2749
2746
        self.add_cleanup(tree.lock_read().unlock)
2750
2747
        for path, file_class, kind, file_id, entry in tree.list_files():
2751
2748
            if file_class != 'I':
2763
2760
    """
2764
2761
    hidden = True
2765
2762
    takes_args = ['revno']
 
2763
    takes_options = ['directory']
2766
2764
 
2767
2765
    @display_command
2768
 
    def run(self, revno):
 
2766
    def run(self, revno, directory=u'.'):
2769
2767
        try:
2770
2768
            revno = int(revno)
2771
2769
        except ValueError:
2772
2770
            raise errors.BzrCommandError("not a valid revision-number: %r"
2773
2771
                                         % revno)
2774
 
        revid = WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
2772
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2775
2773
        self.outf.write("%s\n" % revid)
2776
2774
 
2777
2775
 
2804
2802
      =================       =========================
2805
2803
    """
2806
2804
    takes_args = ['dest', 'branch_or_subdir?']
2807
 
    takes_options = [
 
2805
    takes_options = ['directory',
2808
2806
        Option('format',
2809
2807
               help="Type of file to export to.",
2810
2808
               type=unicode),
2819
2817
                    'revision in which it was changed.'),
2820
2818
        ]
2821
2819
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2822
 
        root=None, filters=False, per_file_timestamps=False):
 
2820
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2823
2821
        from bzrlib.export import export
2824
2822
 
2825
2823
        if branch_or_subdir is None:
2826
 
            tree = WorkingTree.open_containing(u'.')[0]
 
2824
            tree = WorkingTree.open_containing(directory)[0]
2827
2825
            b = tree.branch
2828
2826
            subdir = None
2829
2827
        else:
2848
2846
    """
2849
2847
 
2850
2848
    _see_also = ['ls']
2851
 
    takes_options = [
 
2849
    takes_options = ['directory',
2852
2850
        Option('name-from-revision', help='The path name in the old tree.'),
2853
2851
        Option('filters', help='Apply content filters to display the '
2854
2852
                'convenience form.'),
2859
2857
 
2860
2858
    @display_command
2861
2859
    def run(self, filename, revision=None, name_from_revision=False,
2862
 
            filters=False):
 
2860
            filters=False, directory=None):
2863
2861
        if revision is not None and len(revision) != 1:
2864
2862
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2865
2863
                                         " one revision specifier")
2866
2864
        tree, branch, relpath = \
2867
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2865
            _open_directory_or_containing_tree_or_branch(filename, directory)
2868
2866
        self.add_cleanup(branch.lock_read().unlock)
2869
2867
        return self._run(tree, branch, relpath, filename, revision,
2870
2868
                         name_from_revision, filters)
3101
3099
 
3102
3100
        properties = {}
3103
3101
 
3104
 
        tree, selected_list = tree_files(selected_list)
 
3102
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
3105
3103
        if selected_list == ['']:
3106
3104
            # workaround - commit of root of tree should be exactly the same
3107
3105
            # as just default commit in that tree, and succeed even though
3142
3140
        def get_message(commit_obj):
3143
3141
            """Callback to get commit message"""
3144
3142
            if file:
3145
 
                my_message = codecs.open(
3146
 
                    file, 'rt', osutils.get_user_encoding()).read()
 
3143
                f = open(file)
 
3144
                try:
 
3145
                    my_message = f.read().decode(osutils.get_user_encoding())
 
3146
                finally:
 
3147
                    f.close()
3147
3148
            elif message is not None:
3148
3149
                my_message = message
3149
3150
            else:
3178
3179
                        reporter=None, verbose=verbose, revprops=properties,
3179
3180
                        authors=author, timestamp=commit_stamp,
3180
3181
                        timezone=offset,
3181
 
                        exclude=safe_relpath_files(tree, exclude))
 
3182
                        exclude=tree.safe_relpath_files(exclude))
3182
3183
        except PointlessCommit:
3183
3184
            raise errors.BzrCommandError("No changes to commit."
3184
3185
                              " Use --unchanged to commit anyhow.")
3303
3304
 
3304
3305
            bzr whoami "Frank Chu <fchu@example.com>"
3305
3306
    """
3306
 
    takes_options = [ Option('email',
 
3307
    takes_options = [ 'directory',
 
3308
                      Option('email',
3307
3309
                             help='Display email address only.'),
3308
3310
                      Option('branch',
3309
3311
                             help='Set identity for the current branch instead of '
3313
3315
    encoding_type = 'replace'
3314
3316
 
3315
3317
    @display_command
3316
 
    def run(self, email=False, branch=False, name=None):
 
3318
    def run(self, email=False, branch=False, name=None, directory=None):
3317
3319
        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()
 
3320
            if directory is None:
 
3321
                # use branch if we're inside one; otherwise global config
 
3322
                try:
 
3323
                    c = Branch.open_containing(u'.')[0].get_config()
 
3324
                except errors.NotBranchError:
 
3325
                    c = _mod_config.GlobalConfig()
 
3326
            else:
 
3327
                c = Branch.open(directory).get_config()
3323
3328
            if email:
3324
3329
                self.outf.write(c.user_email() + '\n')
3325
3330
            else:
3328
3333
 
3329
3334
        # display a warning if an email address isn't included in the given name.
3330
3335
        try:
3331
 
            config.extract_email_address(name)
 
3336
            _mod_config.extract_email_address(name)
3332
3337
        except errors.NoEmailInUsername, e:
3333
3338
            warning('"%s" does not seem to contain an email address.  '
3334
3339
                    'This is allowed, but not recommended.', name)
3335
3340
 
3336
3341
        # use global config unless --branch given
3337
3342
        if branch:
3338
 
            c = Branch.open_containing('.')[0].get_config()
 
3343
            if directory is None:
 
3344
                c = Branch.open_containing(u'.')[0].get_config()
 
3345
            else:
 
3346
                c = Branch.open(directory).get_config()
3339
3347
        else:
3340
 
            c = config.GlobalConfig()
 
3348
            c = _mod_config.GlobalConfig()
3341
3349
        c.set_user_option('email', name)
3342
3350
 
3343
3351
 
3353
3361
 
3354
3362
    _see_also = ['info']
3355
3363
    takes_args = ['nickname?']
3356
 
    def run(self, nickname=None):
3357
 
        branch = Branch.open_containing(u'.')[0]
 
3364
    takes_options = ['directory']
 
3365
    def run(self, nickname=None, directory=u'.'):
 
3366
        branch = Branch.open_containing(directory)[0]
3358
3367
        if nickname is None:
3359
3368
            self.printme(branch)
3360
3369
        else:
3409
3418
                'bzr alias --remove expects an alias to remove.')
3410
3419
        # If alias is not found, print something like:
3411
3420
        # unalias: foo: not found
3412
 
        c = config.GlobalConfig()
 
3421
        c = _mod_config.GlobalConfig()
3413
3422
        c.unset_alias(alias_name)
3414
3423
 
3415
3424
    @display_command
3416
3425
    def print_aliases(self):
3417
3426
        """Print out the defined aliases in a similar format to bash."""
3418
 
        aliases = config.GlobalConfig().get_aliases()
 
3427
        aliases = _mod_config.GlobalConfig().get_aliases()
3419
3428
        for key, value in sorted(aliases.iteritems()):
3420
3429
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
3421
3430
 
3431
3440
 
3432
3441
    def set_alias(self, alias_name, alias_command):
3433
3442
        """Save the alias in the global config."""
3434
 
        c = config.GlobalConfig()
 
3443
        c = _mod_config.GlobalConfig()
3435
3444
        c.set_alias(alias_name, alias_command)
3436
3445
 
3437
3446
 
3510
3519
                                 'throughout the test suite.',
3511
3520
                            type=get_transport_type),
3512
3521
                     Option('benchmark',
3513
 
                            help='Run the benchmarks rather than selftests.'),
 
3522
                            help='Run the benchmarks rather than selftests.',
 
3523
                            hidden=True),
3514
3524
                     Option('lsprof-timed',
3515
3525
                            help='Generate lsprof output for benchmarked'
3516
3526
                                 ' sections of code.'),
3517
3527
                     Option('lsprof-tests',
3518
3528
                            help='Generate lsprof output for each test.'),
3519
 
                     Option('cache-dir', type=str,
3520
 
                            help='Cache intermediate benchmark output in this '
3521
 
                                 'directory.'),
3522
3529
                     Option('first',
3523
3530
                            help='Run all tests, but run specified tests first.',
3524
3531
                            short_name='f',
3558
3565
 
3559
3566
    def run(self, testspecs_list=None, verbose=False, one=False,
3560
3567
            transport=None, benchmark=None,
3561
 
            lsprof_timed=None, cache_dir=None,
 
3568
            lsprof_timed=None,
3562
3569
            first=False, list_only=False,
3563
3570
            randomize=None, exclude=None, strict=False,
3564
3571
            load_list=None, debugflag=None, starting_with=None, subunit=False,
3565
3572
            parallel=None, lsprof_tests=False):
3566
 
        from bzrlib.tests import selftest
3567
 
        import bzrlib.benchmarks as benchmarks
3568
 
        from bzrlib.benchmarks import tree_creator
3569
 
 
3570
 
        # Make deprecation warnings visible, unless -Werror is set
3571
 
        symbol_versioning.activate_deprecation_warnings(override=False)
3572
 
 
3573
 
        if cache_dir is not None:
3574
 
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
 
3573
        from bzrlib import tests
 
3574
 
3575
3575
        if testspecs_list is not None:
3576
3576
            pattern = '|'.join(testspecs_list)
3577
3577
        else:
3585
3585
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3586
3586
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3587
3587
            # stdout, which would corrupt the subunit stream. 
3588
 
            if sys.platform == "win32" and sys.stdout.fileno() >= 0:
 
3588
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
3589
            # following code can be deleted when it's sufficiently deployed
 
3590
            # -- vila/mgz 20100514
 
3591
            if (sys.platform == "win32"
 
3592
                and getattr(sys.stdout, 'fileno', None) is not None):
3589
3593
                import msvcrt
3590
3594
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3591
3595
        if parallel:
3592
3596
            self.additional_selftest_args.setdefault(
3593
3597
                'suite_decorators', []).append(parallel)
3594
3598
        if benchmark:
3595
 
            test_suite_factory = benchmarks.test_suite
3596
 
            # Unless user explicitly asks for quiet, be verbose in benchmarks
3597
 
            verbose = not is_quiet()
3598
 
            # TODO: should possibly lock the history file...
3599
 
            benchfile = open(".perf_history", "at", buffering=1)
3600
 
            self.add_cleanup(benchfile.close)
3601
 
        else:
3602
 
            test_suite_factory = None
3603
 
            benchfile = None
 
3599
            raise errors.BzrCommandError(
 
3600
                "--benchmark is no longer supported from bzr 2.2; "
 
3601
                "use bzr-usertest instead")
 
3602
        test_suite_factory = None
3604
3603
        selftest_kwargs = {"verbose": verbose,
3605
3604
                          "pattern": pattern,
3606
3605
                          "stop_on_failure": one,
3608
3607
                          "test_suite_factory": test_suite_factory,
3609
3608
                          "lsprof_timed": lsprof_timed,
3610
3609
                          "lsprof_tests": lsprof_tests,
3611
 
                          "bench_history": benchfile,
3612
3610
                          "matching_tests_first": first,
3613
3611
                          "list_only": list_only,
3614
3612
                          "random_seed": randomize,
3619
3617
                          "starting_with": starting_with
3620
3618
                          }
3621
3619
        selftest_kwargs.update(self.additional_selftest_args)
3622
 
        result = selftest(**selftest_kwargs)
 
3620
 
 
3621
        # Make deprecation warnings visible, unless -Werror is set
 
3622
        cleanup = symbol_versioning.activate_deprecation_warnings(
 
3623
            override=False)
 
3624
        try:
 
3625
            result = tests.selftest(**selftest_kwargs)
 
3626
        finally:
 
3627
            cleanup()
3623
3628
        return int(not result)
3624
3629
 
3625
3630
 
3764
3769
                ' completely merged into the source, pull from the'
3765
3770
                ' source rather than merging.  When this happens,'
3766
3771
                ' you do not need to commit the result.'),
3767
 
        Option('directory',
 
3772
        custom_help('directory',
3768
3773
               help='Branch to merge into, '
3769
 
                    'rather than the one containing the working directory.',
3770
 
               short_name='d',
3771
 
               type=unicode,
3772
 
               ),
 
3774
                    'rather than the one containing the working directory.'),
3773
3775
        Option('preview', help='Instead of merging, show a diff of the'
3774
3776
               ' merge.'),
3775
3777
        Option('interactive', help='Select changes interactively.',
3875
3877
    def _do_preview(self, merger):
3876
3878
        from bzrlib.diff import show_diff_trees
3877
3879
        result_tree = self._get_preview(merger)
 
3880
        path_encoding = osutils.get_diff_header_encoding()
3878
3881
        show_diff_trees(merger.this_tree, result_tree, self.outf,
3879
 
                        old_label='', new_label='')
 
3882
                        old_label='', new_label='',
 
3883
                        path_encoding=path_encoding)
3880
3884
 
3881
3885
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3882
3886
        merger.change_reporter = change_reporter
4069
4073
        from bzrlib.conflicts import restore
4070
4074
        if merge_type is None:
4071
4075
            merge_type = _mod_merge.Merge3Merger
4072
 
        tree, file_list = tree_files(file_list)
 
4076
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4073
4077
        self.add_cleanup(tree.lock_write().unlock)
4074
4078
        parents = tree.get_parent_ids()
4075
4079
        if len(parents) != 2:
4185
4189
 
4186
4190
    def run(self, revision=None, no_backup=False, file_list=None,
4187
4191
            forget_merges=None):
4188
 
        tree, file_list = tree_files(file_list)
 
4192
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4189
4193
        self.add_cleanup(tree.lock_tree_write().unlock)
4190
4194
        if forget_merges:
4191
4195
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4281
4285
    _see_also = ['merge', 'pull']
4282
4286
    takes_args = ['other_branch?']
4283
4287
    takes_options = [
 
4288
        'directory',
4284
4289
        Option('reverse', 'Reverse the order of revisions.'),
4285
4290
        Option('mine-only',
4286
4291
               'Display changes in the local branch only.'),
4308
4313
            theirs_only=False,
4309
4314
            log_format=None, long=False, short=False, line=False,
4310
4315
            show_ids=False, verbose=False, this=False, other=False,
4311
 
            include_merges=False, revision=None, my_revision=None):
 
4316
            include_merges=False, revision=None, my_revision=None,
 
4317
            directory=u'.'):
4312
4318
        from bzrlib.missing import find_unmerged, iter_log_revisions
4313
4319
        def message(s):
4314
4320
            if not is_quiet():
4327
4333
        elif theirs_only:
4328
4334
            restrict = 'remote'
4329
4335
 
4330
 
        local_branch = Branch.open_containing(u".")[0]
 
4336
        local_branch = Branch.open_containing(directory)[0]
4331
4337
        self.add_cleanup(local_branch.lock_read().unlock)
4332
4338
 
4333
4339
        parent = local_branch.get_parent()
4542
4548
                     Option('long', help='Show commit date in annotations.'),
4543
4549
                     'revision',
4544
4550
                     'show-ids',
 
4551
                     'directory',
4545
4552
                     ]
4546
4553
    encoding_type = 'exact'
4547
4554
 
4548
4555
    @display_command
4549
4556
    def run(self, filename, all=False, long=False, revision=None,
4550
 
            show_ids=False):
 
4557
            show_ids=False, directory=None):
4551
4558
        from bzrlib.annotate import annotate_file, annotate_file_tree
4552
4559
        wt, branch, relpath = \
4553
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
4560
            _open_directory_or_containing_tree_or_branch(filename, directory)
4554
4561
        if wt is not None:
4555
4562
            self.add_cleanup(wt.lock_read().unlock)
4556
4563
        else:
4580
4587
 
4581
4588
    hidden = True # is this right ?
4582
4589
    takes_args = ['revision_id*']
4583
 
    takes_options = ['revision']
 
4590
    takes_options = ['directory', 'revision']
4584
4591
 
4585
 
    def run(self, revision_id_list=None, revision=None):
 
4592
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
4586
4593
        if revision_id_list is not None and revision is not None:
4587
4594
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4588
4595
        if revision_id_list is None and revision is None:
4589
4596
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4590
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
4597
        b = WorkingTree.open_containing(directory)[0].branch
4591
4598
        self.add_cleanup(b.lock_write().unlock)
4592
4599
        return self._run(b, revision_id_list, revision)
4593
4600
 
4653
4660
 
4654
4661
    _see_also = ['checkouts', 'unbind']
4655
4662
    takes_args = ['location?']
4656
 
    takes_options = []
 
4663
    takes_options = ['directory']
4657
4664
 
4658
 
    def run(self, location=None):
4659
 
        b, relpath = Branch.open_containing(u'.')
 
4665
    def run(self, location=None, directory=u'.'):
 
4666
        b, relpath = Branch.open_containing(directory)
4660
4667
        if location is None:
4661
4668
            try:
4662
4669
                location = b.get_old_bound_location()
4689
4696
 
4690
4697
    _see_also = ['checkouts', 'bind']
4691
4698
    takes_args = []
4692
 
    takes_options = []
 
4699
    takes_options = ['directory']
4693
4700
 
4694
 
    def run(self):
4695
 
        b, relpath = Branch.open_containing(u'.')
 
4701
    def run(self, directory=u'.'):
 
4702
        b, relpath = Branch.open_containing(directory)
4696
4703
        if not b.unbind():
4697
4704
            raise errors.BzrCommandError('Local branch is not bound')
4698
4705
 
4804
4811
 
4805
4812
 
4806
4813
class cmd_break_lock(Command):
4807
 
    __doc__ = """Break a dead lock on a repository, branch or working directory.
 
4814
    __doc__ = """Break a dead lock.
 
4815
 
 
4816
    This command breaks a lock on a repository, branch, working directory or
 
4817
    config file.
4808
4818
 
4809
4819
    CAUTION: Locks should only be broken when you are sure that the process
4810
4820
    holding the lock has been stopped.
4815
4825
    :Examples:
4816
4826
        bzr break-lock
4817
4827
        bzr break-lock bzr+ssh://example.com/bzr/foo
 
4828
        bzr break-lock --conf ~/.bazaar
4818
4829
    """
 
4830
 
4819
4831
    takes_args = ['location?']
 
4832
    takes_options = [
 
4833
        Option('config',
 
4834
               help='LOCATION is the directory where the config lock is.'),
 
4835
        ]
4820
4836
 
4821
 
    def run(self, location=None, show=False):
 
4837
    def run(self, location=None, config=False):
4822
4838
        if location is None:
4823
4839
            location = u'.'
4824
 
        control, relpath = bzrdir.BzrDir.open_containing(location)
4825
 
        try:
4826
 
            control.break_lock()
4827
 
        except NotImplementedError:
4828
 
            pass
 
4840
        if config:
 
4841
            conf = _mod_config.LockableConfig(file_name=location)
 
4842
            conf.break_lock()
 
4843
        else:
 
4844
            control, relpath = bzrdir.BzrDir.open_containing(location)
 
4845
            try:
 
4846
                control.break_lock()
 
4847
            except NotImplementedError:
 
4848
                pass
4829
4849
 
4830
4850
 
4831
4851
class cmd_wait_until_signalled(Command):
4860
4880
                    'result in a dynamically allocated port.  The default port '
4861
4881
                    'depends on the protocol.',
4862
4882
               type=str),
4863
 
        Option('directory',
4864
 
               help='Serve contents of this directory.',
4865
 
               type=unicode),
 
4883
        custom_help('directory',
 
4884
               help='Serve contents of this directory.'),
4866
4885
        Option('allow-writes',
4867
4886
               help='By default the server is a readonly server.  Supplying '
4868
4887
                    '--allow-writes enables write access to the contents of '
4895
4914
 
4896
4915
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
4897
4916
            protocol=None):
4898
 
        from bzrlib.transport import get_transport, transport_server_registry
 
4917
        from bzrlib import transport
4899
4918
        if directory is None:
4900
4919
            directory = os.getcwd()
4901
4920
        if protocol is None:
4902
 
            protocol = transport_server_registry.get()
 
4921
            protocol = transport.transport_server_registry.get()
4903
4922
        host, port = self.get_host_and_port(port)
4904
4923
        url = urlutils.local_path_to_url(directory)
4905
4924
        if not allow_writes:
4906
4925
            url = 'readonly+' + url
4907
 
        transport = get_transport(url)
4908
 
        protocol(transport, host, port, inet)
 
4926
        t = transport.get_transport(url)
 
4927
        protocol(t, host, port, inet)
4909
4928
 
4910
4929
 
4911
4930
class cmd_join(Command):
5004
5023
    _see_also = ['send']
5005
5024
 
5006
5025
    takes_options = [
 
5026
        'directory',
5007
5027
        RegistryOption.from_kwargs('patch-type',
5008
5028
            'The type of patch to include in the directive.',
5009
5029
            title='Patch type',
5022
5042
    encoding_type = 'exact'
5023
5043
 
5024
5044
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5025
 
            sign=False, revision=None, mail_to=None, message=None):
 
5045
            sign=False, revision=None, mail_to=None, message=None,
 
5046
            directory=u'.'):
5026
5047
        from bzrlib.revision import ensure_null, NULL_REVISION
5027
5048
        include_patch, include_bundle = {
5028
5049
            'plain': (False, False),
5029
5050
            'diff': (True, False),
5030
5051
            'bundle': (True, True),
5031
5052
            }[patch_type]
5032
 
        branch = Branch.open('.')
 
5053
        branch = Branch.open(directory)
5033
5054
        stored_submit_branch = branch.get_submit_branch()
5034
5055
        if submit_branch is None:
5035
5056
            submit_branch = stored_submit_branch
5120
5141
    given, in which case it is sent to a file.
5121
5142
 
5122
5143
    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.
 
5144
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
5124
5145
    If the preferred client can't be found (or used), your editor will be used.
5125
5146
 
5126
5147
    To use a specific mail program, set the mail_client configuration option.
5297
5318
        Option('delete',
5298
5319
            help='Delete this tag rather than placing it.',
5299
5320
            ),
5300
 
        Option('directory',
5301
 
            help='Branch in which to place the tag.',
5302
 
            short_name='d',
5303
 
            type=unicode,
5304
 
            ),
 
5321
        custom_help('directory',
 
5322
            help='Branch in which to place the tag.'),
5305
5323
        Option('force',
5306
5324
            help='Replace existing tags.',
5307
5325
            ),
5349
5367
 
5350
5368
    _see_also = ['tag']
5351
5369
    takes_options = [
5352
 
        Option('directory',
5353
 
            help='Branch whose tags should be displayed.',
5354
 
            short_name='d',
5355
 
            type=unicode,
5356
 
            ),
 
5370
        custom_help('directory',
 
5371
            help='Branch whose tags should be displayed.'),
5357
5372
        RegistryOption.from_kwargs('sort',
5358
5373
            'Sort tags by different criteria.', title='Sorting',
5359
5374
            alpha='Sort tags lexicographically (default).',
5529
5544
    """
5530
5545
 
5531
5546
    takes_args = ['to_location?']
5532
 
    takes_options = [Option('force',
 
5547
    takes_options = ['directory',
 
5548
                     Option('force',
5533
5549
                        help='Switch even if local commits will be lost.'),
5534
5550
                     'revision',
5535
5551
                     Option('create-branch', short_name='b',
5538
5554
                    ]
5539
5555
 
5540
5556
    def run(self, to_location=None, force=False, create_branch=False,
5541
 
            revision=None):
 
5557
            revision=None, directory=u'.'):
5542
5558
        from bzrlib import switch
5543
 
        tree_location = '.'
 
5559
        tree_location = directory
5544
5560
        revision = _get_one_revision('switch', revision)
5545
5561
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5546
5562
        if to_location is None:
5547
5563
            if revision is None:
5548
5564
                raise errors.BzrCommandError('You must supply either a'
5549
5565
                                             ' revision or a location')
5550
 
            to_location = '.'
 
5566
            to_location = tree_location
5551
5567
        try:
5552
5568
            branch = control_dir.open_branch()
5553
5569
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5688
5704
            name=None,
5689
5705
            switch=None,
5690
5706
            ):
5691
 
        tree, file_list = tree_files(file_list, apply_view=False)
 
5707
        tree, file_list = WorkingTree.open_containing_paths(file_list,
 
5708
            apply_view=False)
5692
5709
        current_view, view_dict = tree.views.get_view_info()
5693
5710
        if name is None:
5694
5711
            name = current_view
5828
5845
    takes_args = ['file*']
5829
5846
 
5830
5847
    takes_options = [
 
5848
        'directory',
5831
5849
        'revision',
5832
5850
        Option('all', help='Shelve all changes.'),
5833
5851
        'message',
5842
5860
    _see_also = ['unshelve']
5843
5861
 
5844
5862
    def run(self, revision=None, all=False, file_list=None, message=None,
5845
 
            writer=None, list=False, destroy=False):
 
5863
            writer=None, list=False, destroy=False, directory=u'.'):
5846
5864
        if list:
5847
5865
            return self.run_for_list()
5848
5866
        from bzrlib.shelf_ui import Shelver
5850
5868
            writer = bzrlib.option.diff_writer_registry.get()
5851
5869
        try:
5852
5870
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5853
 
                file_list, message, destroy=destroy)
 
5871
                file_list, message, destroy=destroy, directory=directory)
5854
5872
            try:
5855
5873
                shelver.run()
5856
5874
            finally:
5884
5902
 
5885
5903
    takes_args = ['shelf_id?']
5886
5904
    takes_options = [
 
5905
        'directory',
5887
5906
        RegistryOption.from_kwargs(
5888
5907
            'action', help="The action to perform.",
5889
5908
            enum_switch=False, value_switches=True,
5897
5916
    ]
5898
5917
    _see_also = ['shelve']
5899
5918
 
5900
 
    def run(self, shelf_id=None, action='apply'):
 
5919
    def run(self, shelf_id=None, action='apply', directory=u'.'):
5901
5920
        from bzrlib.shelf_ui import Unshelver
5902
 
        unshelver = Unshelver.from_args(shelf_id, action)
 
5921
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5903
5922
        try:
5904
5923
            unshelver.run()
5905
5924
        finally:
5921
5940
 
5922
5941
    To check what clean-tree will do, use --dry-run.
5923
5942
    """
5924
 
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5943
    takes_options = ['directory',
 
5944
                     Option('ignored', help='Delete all ignored files.'),
5925
5945
                     Option('detritus', help='Delete conflict files, merge'
5926
5946
                            ' backups, and failed selftest dirs.'),
5927
5947
                     Option('unknown',
5930
5950
                            ' deleting them.'),
5931
5951
                     Option('force', help='Do not prompt before deleting.')]
5932
5952
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5933
 
            force=False):
 
5953
            force=False, directory=u'.'):
5934
5954
        from bzrlib.clean_tree import clean_tree
5935
5955
        if not (unknown or ignored or detritus):
5936
5956
            unknown = True
5937
5957
        if dry_run:
5938
5958
            force = True
5939
 
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
5940
 
                   dry_run=dry_run, no_prompt=force)
 
5959
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
5960
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
5941
5961
 
5942
5962
 
5943
5963
class cmd_reference(Command):