~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Vincent Ladeuil
  • Date: 2010-08-20 09:52:25 UTC
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: v.ladeuil+lp@free.fr-20100820095225-wijo4emfgvtmu2ku
BzrRemoveChangedFilesError is deprecated in 2.3.

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
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 = 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:
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
3348
            c = config.GlobalConfig()
3341
3349
        c.set_user_option('email', name)
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:
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
3573
        from bzrlib.tests import selftest
3567
 
        import bzrlib.benchmarks as benchmarks
3568
 
        from bzrlib.benchmarks import tree_creator
3569
3574
 
3570
3575
        # Make deprecation warnings visible, unless -Werror is set
3571
3576
        symbol_versioning.activate_deprecation_warnings(override=False)
3572
3577
 
3573
 
        if cache_dir is not None:
3574
 
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3575
3578
        if testspecs_list is not None:
3576
3579
            pattern = '|'.join(testspecs_list)
3577
3580
        else:
3585
3588
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3586
3589
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3587
3590
            # stdout, which would corrupt the subunit stream. 
3588
 
            if sys.platform == "win32" and sys.stdout.fileno() >= 0:
 
3591
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
3592
            # following code can be deleted when it's sufficiently deployed
 
3593
            # -- vila/mgz 20100514
 
3594
            if (sys.platform == "win32"
 
3595
                and getattr(sys.stdout, 'fileno', None) is not None):
3589
3596
                import msvcrt
3590
3597
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3591
3598
        if parallel:
3592
3599
            self.additional_selftest_args.setdefault(
3593
3600
                'suite_decorators', []).append(parallel)
3594
3601
        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
 
3602
            raise errors.BzrCommandError(
 
3603
                "--benchmark is no longer supported from bzr 2.2; "
 
3604
                "use bzr-usertest instead")
 
3605
        test_suite_factory = None
3604
3606
        selftest_kwargs = {"verbose": verbose,
3605
3607
                          "pattern": pattern,
3606
3608
                          "stop_on_failure": one,
3608
3610
                          "test_suite_factory": test_suite_factory,
3609
3611
                          "lsprof_timed": lsprof_timed,
3610
3612
                          "lsprof_tests": lsprof_tests,
3611
 
                          "bench_history": benchfile,
3612
3613
                          "matching_tests_first": first,
3613
3614
                          "list_only": list_only,
3614
3615
                          "random_seed": randomize,
3764
3765
                ' completely merged into the source, pull from the'
3765
3766
                ' source rather than merging.  When this happens,'
3766
3767
                ' you do not need to commit the result.'),
3767
 
        Option('directory',
 
3768
        custom_help('directory',
3768
3769
               help='Branch to merge into, '
3769
 
                    'rather than the one containing the working directory.',
3770
 
               short_name='d',
3771
 
               type=unicode,
3772
 
               ),
 
3770
                    'rather than the one containing the working directory.'),
3773
3771
        Option('preview', help='Instead of merging, show a diff of the'
3774
3772
               ' merge.'),
3775
3773
        Option('interactive', help='Select changes interactively.',
3875
3873
    def _do_preview(self, merger):
3876
3874
        from bzrlib.diff import show_diff_trees
3877
3875
        result_tree = self._get_preview(merger)
 
3876
        path_encoding = osutils.get_diff_header_encoding()
3878
3877
        show_diff_trees(merger.this_tree, result_tree, self.outf,
3879
 
                        old_label='', new_label='')
 
3878
                        old_label='', new_label='',
 
3879
                        path_encoding=path_encoding)
3880
3880
 
3881
3881
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3882
3882
        merger.change_reporter = change_reporter
4069
4069
        from bzrlib.conflicts import restore
4070
4070
        if merge_type is None:
4071
4071
            merge_type = _mod_merge.Merge3Merger
4072
 
        tree, file_list = tree_files(file_list)
 
4072
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4073
4073
        self.add_cleanup(tree.lock_write().unlock)
4074
4074
        parents = tree.get_parent_ids()
4075
4075
        if len(parents) != 2:
4185
4185
 
4186
4186
    def run(self, revision=None, no_backup=False, file_list=None,
4187
4187
            forget_merges=None):
4188
 
        tree, file_list = tree_files(file_list)
 
4188
        tree, file_list = WorkingTree.open_containing_paths(file_list)
4189
4189
        self.add_cleanup(tree.lock_tree_write().unlock)
4190
4190
        if forget_merges:
4191
4191
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4281
4281
    _see_also = ['merge', 'pull']
4282
4282
    takes_args = ['other_branch?']
4283
4283
    takes_options = [
 
4284
        'directory',
4284
4285
        Option('reverse', 'Reverse the order of revisions.'),
4285
4286
        Option('mine-only',
4286
4287
               'Display changes in the local branch only.'),
4308
4309
            theirs_only=False,
4309
4310
            log_format=None, long=False, short=False, line=False,
4310
4311
            show_ids=False, verbose=False, this=False, other=False,
4311
 
            include_merges=False, revision=None, my_revision=None):
 
4312
            include_merges=False, revision=None, my_revision=None,
 
4313
            directory=u'.'):
4312
4314
        from bzrlib.missing import find_unmerged, iter_log_revisions
4313
4315
        def message(s):
4314
4316
            if not is_quiet():
4327
4329
        elif theirs_only:
4328
4330
            restrict = 'remote'
4329
4331
 
4330
 
        local_branch = Branch.open_containing(u".")[0]
 
4332
        local_branch = Branch.open_containing(directory)[0]
4331
4333
        self.add_cleanup(local_branch.lock_read().unlock)
4332
4334
 
4333
4335
        parent = local_branch.get_parent()
4542
4544
                     Option('long', help='Show commit date in annotations.'),
4543
4545
                     'revision',
4544
4546
                     'show-ids',
 
4547
                     'directory',
4545
4548
                     ]
4546
4549
    encoding_type = 'exact'
4547
4550
 
4548
4551
    @display_command
4549
4552
    def run(self, filename, all=False, long=False, revision=None,
4550
 
            show_ids=False):
 
4553
            show_ids=False, directory=None):
4551
4554
        from bzrlib.annotate import annotate_file, annotate_file_tree
4552
4555
        wt, branch, relpath = \
4553
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
4556
            _open_directory_or_containing_tree_or_branch(filename, directory)
4554
4557
        if wt is not None:
4555
4558
            self.add_cleanup(wt.lock_read().unlock)
4556
4559
        else:
4580
4583
 
4581
4584
    hidden = True # is this right ?
4582
4585
    takes_args = ['revision_id*']
4583
 
    takes_options = ['revision']
 
4586
    takes_options = ['directory', 'revision']
4584
4587
 
4585
 
    def run(self, revision_id_list=None, revision=None):
 
4588
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
4586
4589
        if revision_id_list is not None and revision is not None:
4587
4590
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4588
4591
        if revision_id_list is None and revision is None:
4589
4592
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4590
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
4593
        b = WorkingTree.open_containing(directory)[0].branch
4591
4594
        self.add_cleanup(b.lock_write().unlock)
4592
4595
        return self._run(b, revision_id_list, revision)
4593
4596
 
4653
4656
 
4654
4657
    _see_also = ['checkouts', 'unbind']
4655
4658
    takes_args = ['location?']
4656
 
    takes_options = []
 
4659
    takes_options = ['directory']
4657
4660
 
4658
 
    def run(self, location=None):
4659
 
        b, relpath = Branch.open_containing(u'.')
 
4661
    def run(self, location=None, directory=u'.'):
 
4662
        b, relpath = Branch.open_containing(directory)
4660
4663
        if location is None:
4661
4664
            try:
4662
4665
                location = b.get_old_bound_location()
4689
4692
 
4690
4693
    _see_also = ['checkouts', 'bind']
4691
4694
    takes_args = []
4692
 
    takes_options = []
 
4695
    takes_options = ['directory']
4693
4696
 
4694
 
    def run(self):
4695
 
        b, relpath = Branch.open_containing(u'.')
 
4697
    def run(self, directory=u'.'):
 
4698
        b, relpath = Branch.open_containing(directory)
4696
4699
        if not b.unbind():
4697
4700
            raise errors.BzrCommandError('Local branch is not bound')
4698
4701
 
4860
4863
                    'result in a dynamically allocated port.  The default port '
4861
4864
                    'depends on the protocol.',
4862
4865
               type=str),
4863
 
        Option('directory',
4864
 
               help='Serve contents of this directory.',
4865
 
               type=unicode),
 
4866
        custom_help('directory',
 
4867
               help='Serve contents of this directory.'),
4866
4868
        Option('allow-writes',
4867
4869
               help='By default the server is a readonly server.  Supplying '
4868
4870
                    '--allow-writes enables write access to the contents of '
4895
4897
 
4896
4898
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
4897
4899
            protocol=None):
4898
 
        from bzrlib.transport import get_transport, transport_server_registry
 
4900
        from bzrlib import transport
4899
4901
        if directory is None:
4900
4902
            directory = os.getcwd()
4901
4903
        if protocol is None:
4902
 
            protocol = transport_server_registry.get()
 
4904
            protocol = transport.transport_server_registry.get()
4903
4905
        host, port = self.get_host_and_port(port)
4904
4906
        url = urlutils.local_path_to_url(directory)
4905
4907
        if not allow_writes:
4906
4908
            url = 'readonly+' + url
4907
 
        transport = get_transport(url)
4908
 
        protocol(transport, host, port, inet)
 
4909
        t = transport.get_transport(url)
 
4910
        protocol(t, host, port, inet)
4909
4911
 
4910
4912
 
4911
4913
class cmd_join(Command):
5004
5006
    _see_also = ['send']
5005
5007
 
5006
5008
    takes_options = [
 
5009
        'directory',
5007
5010
        RegistryOption.from_kwargs('patch-type',
5008
5011
            'The type of patch to include in the directive.',
5009
5012
            title='Patch type',
5022
5025
    encoding_type = 'exact'
5023
5026
 
5024
5027
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5025
 
            sign=False, revision=None, mail_to=None, message=None):
 
5028
            sign=False, revision=None, mail_to=None, message=None,
 
5029
            directory=u'.'):
5026
5030
        from bzrlib.revision import ensure_null, NULL_REVISION
5027
5031
        include_patch, include_bundle = {
5028
5032
            'plain': (False, False),
5029
5033
            'diff': (True, False),
5030
5034
            'bundle': (True, True),
5031
5035
            }[patch_type]
5032
 
        branch = Branch.open('.')
 
5036
        branch = Branch.open(directory)
5033
5037
        stored_submit_branch = branch.get_submit_branch()
5034
5038
        if submit_branch is None:
5035
5039
            submit_branch = stored_submit_branch
5120
5124
    given, in which case it is sent to a file.
5121
5125
 
5122
5126
    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.
 
5127
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
5124
5128
    If the preferred client can't be found (or used), your editor will be used.
5125
5129
 
5126
5130
    To use a specific mail program, set the mail_client configuration option.
5297
5301
        Option('delete',
5298
5302
            help='Delete this tag rather than placing it.',
5299
5303
            ),
5300
 
        Option('directory',
5301
 
            help='Branch in which to place the tag.',
5302
 
            short_name='d',
5303
 
            type=unicode,
5304
 
            ),
 
5304
        custom_help('directory',
 
5305
            help='Branch in which to place the tag.'),
5305
5306
        Option('force',
5306
5307
            help='Replace existing tags.',
5307
5308
            ),
5349
5350
 
5350
5351
    _see_also = ['tag']
5351
5352
    takes_options = [
5352
 
        Option('directory',
5353
 
            help='Branch whose tags should be displayed.',
5354
 
            short_name='d',
5355
 
            type=unicode,
5356
 
            ),
 
5353
        custom_help('directory',
 
5354
            help='Branch whose tags should be displayed.'),
5357
5355
        RegistryOption.from_kwargs('sort',
5358
5356
            'Sort tags by different criteria.', title='Sorting',
5359
5357
            alpha='Sort tags lexicographically (default).',
5529
5527
    """
5530
5528
 
5531
5529
    takes_args = ['to_location?']
5532
 
    takes_options = [Option('force',
 
5530
    takes_options = ['directory',
 
5531
                     Option('force',
5533
5532
                        help='Switch even if local commits will be lost.'),
5534
5533
                     'revision',
5535
5534
                     Option('create-branch', short_name='b',
5538
5537
                    ]
5539
5538
 
5540
5539
    def run(self, to_location=None, force=False, create_branch=False,
5541
 
            revision=None):
 
5540
            revision=None, directory=u'.'):
5542
5541
        from bzrlib import switch
5543
 
        tree_location = '.'
 
5542
        tree_location = directory
5544
5543
        revision = _get_one_revision('switch', revision)
5545
5544
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5546
5545
        if to_location is None:
5547
5546
            if revision is None:
5548
5547
                raise errors.BzrCommandError('You must supply either a'
5549
5548
                                             ' revision or a location')
5550
 
            to_location = '.'
 
5549
            to_location = tree_location
5551
5550
        try:
5552
5551
            branch = control_dir.open_branch()
5553
5552
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5688
5687
            name=None,
5689
5688
            switch=None,
5690
5689
            ):
5691
 
        tree, file_list = tree_files(file_list, apply_view=False)
 
5690
        tree, file_list = WorkingTree.open_containing_paths(file_list,
 
5691
            apply_view=False)
5692
5692
        current_view, view_dict = tree.views.get_view_info()
5693
5693
        if name is None:
5694
5694
            name = current_view
5828
5828
    takes_args = ['file*']
5829
5829
 
5830
5830
    takes_options = [
 
5831
        'directory',
5831
5832
        'revision',
5832
5833
        Option('all', help='Shelve all changes.'),
5833
5834
        'message',
5842
5843
    _see_also = ['unshelve']
5843
5844
 
5844
5845
    def run(self, revision=None, all=False, file_list=None, message=None,
5845
 
            writer=None, list=False, destroy=False):
 
5846
            writer=None, list=False, destroy=False, directory=u'.'):
5846
5847
        if list:
5847
5848
            return self.run_for_list()
5848
5849
        from bzrlib.shelf_ui import Shelver
5850
5851
            writer = bzrlib.option.diff_writer_registry.get()
5851
5852
        try:
5852
5853
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5853
 
                file_list, message, destroy=destroy)
 
5854
                file_list, message, destroy=destroy, directory=directory)
5854
5855
            try:
5855
5856
                shelver.run()
5856
5857
            finally:
5884
5885
 
5885
5886
    takes_args = ['shelf_id?']
5886
5887
    takes_options = [
 
5888
        'directory',
5887
5889
        RegistryOption.from_kwargs(
5888
5890
            'action', help="The action to perform.",
5889
5891
            enum_switch=False, value_switches=True,
5897
5899
    ]
5898
5900
    _see_also = ['shelve']
5899
5901
 
5900
 
    def run(self, shelf_id=None, action='apply'):
 
5902
    def run(self, shelf_id=None, action='apply', directory=u'.'):
5901
5903
        from bzrlib.shelf_ui import Unshelver
5902
 
        unshelver = Unshelver.from_args(shelf_id, action)
 
5904
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5903
5905
        try:
5904
5906
            unshelver.run()
5905
5907
        finally:
5921
5923
 
5922
5924
    To check what clean-tree will do, use --dry-run.
5923
5925
    """
5924
 
    takes_options = [Option('ignored', help='Delete all ignored files.'),
 
5926
    takes_options = ['directory',
 
5927
                     Option('ignored', help='Delete all ignored files.'),
5925
5928
                     Option('detritus', help='Delete conflict files, merge'
5926
5929
                            ' backups, and failed selftest dirs.'),
5927
5930
                     Option('unknown',
5930
5933
                            ' deleting them.'),
5931
5934
                     Option('force', help='Do not prompt before deleting.')]
5932
5935
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5933
 
            force=False):
 
5936
            force=False, directory=u'.'):
5934
5937
        from bzrlib.clean_tree import clean_tree
5935
5938
        if not (unknown or ignored or detritus):
5936
5939
            unknown = True
5937
5940
        if dry_run:
5938
5941
            force = True
5939
 
        clean_tree('.', unknown=unknown, ignored=ignored, detritus=detritus,
5940
 
                   dry_run=dry_run, no_prompt=force)
 
5942
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
5943
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
5941
5944
 
5942
5945
 
5943
5946
class cmd_reference(Command):