/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5609.16.1 by John Arbash Meinel
Fix bug #713258. Restore logging of bytes transferred.
1
# Copyright (C) 2005-2011 Canonical Ltd
1610.1.4 by Martin Pool
Doc
2
#
1 by mbp at sourcefrog
import from baz patch-364
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1610.1.4 by Martin Pool
Doc
7
#
1 by mbp at sourcefrog
import from baz patch-364
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1610.1.4 by Martin Pool
Doc
12
#
1 by mbp at sourcefrog
import from baz patch-364
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1 by mbp at sourcefrog
import from baz patch-364
16
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
17
from __future__ import absolute_import
1 by mbp at sourcefrog
import from baz patch-364
18
1095 by Martin Pool
todo
19
# TODO: Define arguments by objects, rather than just using names.
20
# Those objects can specify the expected type of the argument, which
1610.1.4 by Martin Pool
Doc
21
# would help with validation and shell completion.  They could also provide
22
# help/explanation for that argument in a structured way.
23
24
# TODO: Specific "examples" property on commands for consistent formatting.
1095 by Martin Pool
todo
25
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
26
import os
27
import sys
28
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
29
from .lazy_import import lazy_import
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
30
lazy_import(globals(), """
1857.1.1 by Aaron Bentley
Use optparse for parsing options
31
import errno
4325.1.1 by Vincent Ladeuil
Make --coverage works for threads too.
32
import threading
1 by mbp at sourcefrog
import from baz patch-364
33
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
34
import breezy
35
from breezy import (
6437.6.3 by Vincent Ladeuil
Add the missing config import.
36
    config,
4900.1.1 by Andrew Bennetts
Add add_cleanup to Command.
37
    cleanup,
4913.5.24 by Gordon Tyler
Added cmdline.split function, which replaces commands.shlex_split_unicode.
38
    cmdline,
2095.5.2 by Martin Pool
save commit message if commit fails (#32054)
39
    debug,
5875.3.25 by Vincent Ladeuil
Fix test failures and make sure we don't rely on a default translation.
40
    i18n,
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
41
    option,
42
    osutils,
43
    trace,
4792.8.9 by Martin Pool
Send Command.outf through UIFactory
44
    ui,
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
45
    )
46
""")
47
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
48
from .hooks import Hooks
49
from .i18n import gettext
4119.3.8 by Robert Collins
Get missing command support sorted out.
50
# Compatibility - Option used to be in commands.
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
51
from .option import Option
6651.4.2 by Martin
Move plugin_name logic from commands to plugin to fix test
52
from .plugin import disable_plugins, load_plugins, plugin_name
6731.1.4 by Jelmer Vernooij
Move BadOptionValue to breezy.option.
53
from . import errors, registry
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
54
from .sixish import (
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
55
    string_types,
56
    )
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
57
1 by mbp at sourcefrog
import from baz patch-364
58
6731.1.4 by Jelmer Vernooij
Move BadOptionValue to breezy.option.
59
class BzrOptionError(errors.BzrCommandError):
60
61
    _fmt = "Error in command line options"
62
63
6734.1.1 by Jelmer Vernooij
Fix more imports.
64
class CommandAvailableInPlugin(Exception):
65
66
    internal_error = False
67
68
    def __init__(self, cmd_name, plugin_metadata, provider):
69
70
        self.plugin_metadata = plugin_metadata
71
        self.cmd_name = cmd_name
72
        self.provider = provider
73
74
    def __str__(self):
75
76
        _fmt = ('"%s" is not a standard brz command. \n'
77
                'However, the following official plugin provides this command: %s\n'
78
                'You can install it by going to: %s'
79
                % (self.cmd_name, self.plugin_metadata['name'],
80
                    self.plugin_metadata['url']))
81
82
        return _fmt
83
84
3785.1.2 by Aaron Bentley
Avoid getting plugins unnecessarily
85
class CommandInfo(object):
86
    """Information about a command."""
87
88
    def __init__(self, aliases):
89
        """The list of aliases for the command."""
90
        self.aliases = aliases
91
92
    @classmethod
93
    def from_command(klass, command):
94
        """Factory to construct a CommandInfo from a command."""
95
        return klass(command.aliases)
96
97
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
98
class CommandRegistry(registry.Registry):
5018.1.9 by Martin Pool
Handle aliases directly in CommandRegistry
99
    """Special registry mapping command names to command classes.
100
    
101
    :ivar overridden_registry: Look in this registry for commands being
102
        overridden by this registry.  This can be used to tell plugin commands
103
        about the builtin they're decorating.
5018.1.6 by Martin Pool
Avoid more cases of using a dict of all builtins
104
    """
105
5018.1.9 by Martin Pool
Handle aliases directly in CommandRegistry
106
    def __init__(self):
107
        registry.Registry.__init__(self)
108
        self.overridden_registry = None
109
        # map from aliases to the real command that implements the name
110
        self._alias_dict = {}
111
112
    def get(self, command_name):
113
        real_name = self._alias_dict.get(command_name, command_name)
114
        return registry.Registry.get(self, real_name)
115
3785.1.4 by Aaron Bentley
Enable lazy-loading of commands
116
    @staticmethod
117
    def _get_name(command_name):
118
        if command_name.startswith("cmd_"):
119
            return _unsquish_command_name(command_name)
120
        else:
121
            return command_name
122
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
123
    def register(self, cmd, decorate=False):
124
        """Utility function to help register a command
125
126
        :param cmd: Command subclass to register
127
        :param decorate: If true, allow overriding an existing command
128
            of the same name; the old command is returned by this function.
129
            Otherwise it is an error to try to override an existing command.
130
        """
131
        k = cmd.__name__
3785.1.4 by Aaron Bentley
Enable lazy-loading of commands
132
        k_unsquished = self._get_name(k)
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
133
        try:
134
            previous = self.get(k_unsquished)
135
        except KeyError:
5018.1.6 by Martin Pool
Avoid more cases of using a dict of all builtins
136
            previous = None
137
            if self.overridden_registry:
138
                try:
139
                    previous = self.overridden_registry.get(k_unsquished)
140
                except KeyError:
141
                    pass
3785.1.2 by Aaron Bentley
Avoid getting plugins unnecessarily
142
        info = CommandInfo.from_command(cmd)
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
143
        try:
144
            registry.Registry.register(self, k_unsquished, cmd,
3785.1.2 by Aaron Bentley
Avoid getting plugins unnecessarily
145
                                       override_existing=decorate, info=info)
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
146
        except KeyError:
4695.5.2 by Martin Pool
Remove trace.log_error
147
            trace.warning('Two plugins defined the same command: %r' % k)
148
            trace.warning('Not loading the one in %r' %
149
                sys.modules[cmd.__module__])
150
            trace.warning('Previously this command was registered from %r' %
151
                sys.modules[previous.__module__])
5018.1.9 by Martin Pool
Handle aliases directly in CommandRegistry
152
        for a in cmd.aliases:
153
            self._alias_dict[a] = k_unsquished
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
154
        return previous
155
3785.1.4 by Aaron Bentley
Enable lazy-loading of commands
156
    def register_lazy(self, command_name, aliases, module_name):
157
        """Register a command without loading its module.
158
159
        :param command_name: The primary name of the command.
160
        :param aliases: A list of aliases for the command.
161
        :module_name: The module that the command lives in.
162
        """
163
        key = self._get_name(command_name)
164
        registry.Registry.register_lazy(self, key, module_name, command_name,
165
                                        info=CommandInfo(aliases))
5018.1.9 by Martin Pool
Handle aliases directly in CommandRegistry
166
        for a in aliases:
167
            self._alias_dict[a] = key
3785.1.4 by Aaron Bentley
Enable lazy-loading of commands
168
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
169
170
plugin_cmds = CommandRegistry()
5018.1.5 by Martin Pool
Rename registry to builtin_command_registry
171
builtin_command_registry = CommandRegistry()
5018.1.6 by Martin Pool
Avoid more cases of using a dict of all builtins
172
plugin_cmds.overridden_registry = builtin_command_registry
731 by Martin Pool
- merge plugin patch from john
173
174
1492 by Robert Collins
Support decoration of commands.
175
def register_command(cmd, decorate=False):
5018.1.7 by Martin Pool
doc
176
    """Register a plugin command.
177
178
    Should generally be avoided in favor of lazy registration. 
179
    """
731 by Martin Pool
- merge plugin patch from john
180
    global plugin_cmds
3785.1.1 by Aaron Bentley
Switch from dict to Registry for plugin_cmds
181
    return plugin_cmds.register(cmd, decorate)
731 by Martin Pool
- merge plugin patch from john
182
183
350 by Martin Pool
- refactor command aliases into command classes
184
def _squish_command_name(cmd):
185
    return 'cmd_' + cmd.replace('-', '_')
186
187
188
def _unsquish_command_name(cmd):
189
    return cmd[4:].replace('_','-')
190
914 by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch
191
5018.1.3 by Martin Pool
Put builtin commands into a real registry
192
def _register_builtin_commands():
5018.1.5 by Martin Pool
Rename registry to builtin_command_registry
193
    if builtin_command_registry.keys():
5018.1.3 by Martin Pool
Put builtin commands into a real registry
194
        # only load once
195
        return
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
196
    import breezy.builtins
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
197
    for cmd_class in _scan_module_for_commands(breezy.builtins):
5018.1.5 by Martin Pool
Rename registry to builtin_command_registry
198
        builtin_command_registry.register(cmd_class)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
199
    breezy.builtins._register_lazy_builtins()
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
200
201
202
def _scan_module_for_commands(module):
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
203
    module_dict = module.__dict__
204
    for name in module_dict:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
205
        if name.startswith("cmd_"):
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
206
            yield module_dict[name]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
207
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
208
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
209
def _list_bzr_commands(names):
5018.1.7 by Martin Pool
doc
210
    """Find commands from bzr's core and plugins.
211
    
212
    This is not the public interface, just the default hook called by all_command_names.
213
    """
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
214
    # to eliminate duplicates
215
    names.update(builtin_command_names())
216
    names.update(plugin_command_names())
217
    return names
218
219
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
220
def all_command_names():
4119.3.10 by Robert Collins
More review feedback.
221
    """Return a set of all command names."""
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
222
    names = set()
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
223
    for hook in Command.hooks['list_commands']:
4119.3.10 by Robert Collins
More review feedback.
224
        names = hook(names)
225
        if names is None:
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
226
            raise AssertionError(
227
                'hook %s returned None' % Command.hooks.get_hook_name(hook))
228
    return names
229
230
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
231
def builtin_command_names():
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
232
    """Return list of builtin command names.
233
    
234
    Use of all_command_names() is encouraged rather than builtin_command_names
235
    and/or plugin_command_names.
236
    """
5255.5.1 by Ian Clatworthy
Ensure builtin_command_names() is initialized correctly
237
    _register_builtin_commands()
5018.1.5 by Martin Pool
Rename registry to builtin_command_registry
238
    return builtin_command_registry.keys()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
239
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
240
241
def plugin_command_names():
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
242
    """Returns command names from commands registered by plugins."""
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
243
    return plugin_cmds.keys()
244
245
6690.5.2 by Jelmer Vernooij
Add tests for guess_command.
246
# Overrides for common mispellings that heuristics get wrong
247
_GUESS_OVERRIDES = {
248
    'ic': {'ci': 0}, # heuristic finds nick
249
    }
250
251
252
def guess_command(cmd_name):
253
    """Guess what command a user typoed.
254
255
    :param cmd_name: Command to search for
256
    :return: None if no command was found, name of a command otherwise
257
    """
258
    names = set()
259
    for name in all_command_names():
260
        names.add(name)
261
        cmd = get_cmd_object(name)
262
        names.update(cmd.aliases)
263
    # candidate: modified levenshtein distance against cmd_name.
264
    costs = {}
265
    from . import patiencediff
266
    for name in sorted(names):
267
        matcher = patiencediff.PatienceSequenceMatcher(None, cmd_name, name)
268
        distance = 0.0
269
        opcodes = matcher.get_opcodes()
270
        for opcode, l1, l2, r1, r2 in opcodes:
271
            if opcode == 'delete':
272
                distance += l2-l1
273
            elif opcode == 'replace':
274
                distance += max(l2-l1, r2-l1)
275
            elif opcode == 'insert':
276
                distance += r2-r1
277
            elif opcode == 'equal':
278
                # Score equal ranges lower, making similar commands of equal
279
                # length closer than arbitrary same length commands.
280
                distance -= 0.1 * (l2-l1)
281
        costs[name] = distance
282
    costs.update(_GUESS_OVERRIDES.get(cmd_name, {}))
283
    costs = sorted((value, key) for key, value in costs.iteritems())
284
    if not costs:
285
        return
286
    if costs[0][0] > 4:
287
        return
288
    candidate = costs[0][1]
289
    return candidate
290
291
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
292
def get_cmd_object(cmd_name, plugins_override=True):
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
293
    """Return the command object for a command.
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
294
295
    plugins_override
296
        If true, plugin commands can override builtins.
350 by Martin Pool
- refactor command aliases into command classes
297
    """
2432.1.13 by Robert Collins
HelpCommandContext now implementes get_topics.
298
    try:
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
299
        return _get_cmd_object(cmd_name, plugins_override)
2432.1.13 by Robert Collins
HelpCommandContext now implementes get_topics.
300
    except KeyError:
6690.5.2 by Jelmer Vernooij
Add tests for guess_command.
301
        # No command found, see if this was a typo
302
        candidate = guess_command(cmd_name)
303
        if candidate is not None:
304
            raise errors.BzrCommandError(
305
                    gettext('unknown command "%s". Perhaps you meant "%s"')
306
                    % (cmd_name, candidate))
307
        raise errors.BzrCommandError(gettext('unknown command "%s"')
308
                % cmd_name)
2432.1.13 by Robert Collins
HelpCommandContext now implementes get_topics.
309
310
5058.2.1 by Robert Collins
* ``bzr help`` will no longer trigger the get_missing_command hook when
311
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
312
    """Get a command object.
313
314
    :param cmd_name: The name of the command.
315
    :param plugins_override: Allow plugins to override builtins.
5058.2.1 by Robert Collins
* ``bzr help`` will no longer trigger the get_missing_command hook when
316
    :param check_missing: Look up commands not found in the regular index via
317
        the get_missing_command hook.
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
318
    :return: A Command object instance
4119.3.10 by Robert Collins
More review feedback.
319
    :raises KeyError: If no command is found.
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
320
    """
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
321
    # We want only 'ascii' command names, but the user may have typed
322
    # in a Unicode name. In that case, they should just get a
323
    # 'command not found' error later.
324
    # In the future, we may actually support Unicode command names.
325
    cmd = None
326
    # Get a command
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
327
    for hook in Command.hooks['get_command']:
328
        cmd = hook(cmd, cmd_name)
4119.3.10 by Robert Collins
More review feedback.
329
        if cmd is not None and not plugins_override and not cmd.plugin_name():
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
330
            # We've found a non-plugin command, don't permit it to be
331
            # overridden.
4119.3.10 by Robert Collins
More review feedback.
332
            break
5058.2.1 by Robert Collins
* ``bzr help`` will no longer trigger the get_missing_command hook when
333
    if cmd is None and check_missing:
4119.3.8 by Robert Collins
Get missing command support sorted out.
334
        for hook in Command.hooks['get_missing_command']:
335
            cmd = hook(cmd_name)
336
            if cmd is not None:
337
                break
338
    if cmd is None:
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
339
        # No command found.
340
        raise KeyError
341
    # Allow plugins to extend commands
6240.5.7 by Jelmer Vernooij
Drop exception suppression support.
342
    for hook in Command.hooks['extend_command']:
343
        hook(cmd)
5741.3.1 by Martin Pool
Add Command.invoked_as
344
    if getattr(cmd, 'invoked_as', None) is None:
345
        cmd.invoked_as = cmd_name
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
346
    return cmd
347
348
6734.1.1 by Jelmer Vernooij
Fix more imports.
349
class NoPluginAvailable(errors.BzrError):
350
    pass
351
352
4119.3.8 by Robert Collins
Get missing command support sorted out.
353
def _try_plugin_provider(cmd_name):
354
    """Probe for a plugin provider having cmd_name."""
355
    try:
356
        plugin_metadata, provider = probe_for_provider(cmd_name)
6734.1.1 by Jelmer Vernooij
Fix more imports.
357
        raise CommandAvailableInPlugin(cmd_name, plugin_metadata, provider)
358
    except NoPluginAvailable:
4119.3.8 by Robert Collins
Get missing command support sorted out.
359
        pass
360
361
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
362
def probe_for_provider(cmd_name):
363
    """Look for a provider for cmd_name.
364
365
    :param cmd_name: The command name.
366
    :return: plugin_metadata, provider for getting cmd_name.
367
    :raises NoPluginAvailable: When no provider can supply the plugin.
368
    """
369
    # look for providers that provide this command but aren't installed
370
    for provider in command_providers_registry:
371
        try:
372
            return provider.plugin_for_command(cmd_name), provider
6734.1.1 by Jelmer Vernooij
Fix more imports.
373
        except NoPluginAvailable:
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
374
            pass
6734.1.1 by Jelmer Vernooij
Fix more imports.
375
    raise NoPluginAvailable(cmd_name)
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
376
377
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
378
def _get_bzr_command(cmd_or_None, cmd_name):
379
    """Get a command from bzr's core."""
272 by Martin Pool
- Add command aliases
380
    try:
5018.1.6 by Martin Pool
Avoid more cases of using a dict of all builtins
381
        cmd_class = builtin_command_registry.get(cmd_name)
272 by Martin Pool
- Add command aliases
382
    except KeyError:
350 by Martin Pool
- refactor command aliases into command classes
383
        pass
5018.1.6 by Martin Pool
Avoid more cases of using a dict of all builtins
384
    else:
385
        return cmd_class()
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
386
    return cmd_or_None
387
388
389
def _get_external_command(cmd_or_None, cmd_name):
390
    """Lookup a command that is a shell script."""
391
    # Only do external command lookups when no command is found so far.
392
    if cmd_or_None is not None:
393
        return cmd_or_None
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
394
    from breezy.externalcommand import ExternalCommand
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
395
    cmd_obj = ExternalCommand.find_command(cmd_name)
396
    if cmd_obj:
397
        return cmd_obj
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
398
399
400
def _get_plugin_command(cmd_or_None, cmd_name):
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
401
    """Get a command from brz's plugins."""
4119.3.6 by Robert Collins
Refactor commands.__get_cmd_object to be default-installed hooks.
402
    try:
403
        return plugin_cmds.get(cmd_name)()
404
    except KeyError:
405
        pass
406
    for key in plugin_cmds.keys():
407
        info = plugin_cmds.get_info(key)
408
        if cmd_name in info.aliases:
409
            return plugin_cmds.get(key)()
410
    return cmd_or_None
272 by Martin Pool
- Add command aliases
411
329 by Martin Pool
- refactor command functions into command classes
412
558 by Martin Pool
- All top-level classes inherit from object
413
class Command(object):
329 by Martin Pool
- refactor command functions into command classes
414
    """Base class for commands.
415
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
416
    Commands are the heart of the command-line brz interface.
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
417
418
    The command object mostly handles the mapping of command-line
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
419
    parameters into one or more breezy operations, and of the results
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
420
    into textual output.
421
422
    Commands normally don't have any state.  All their arguments are
423
    passed in to the run method.  (Subclasses may take a different
424
    policy if the behaviour of the instance needs to depend on e.g. a
425
    shell plugin and not just its Python class.)
426
329 by Martin Pool
- refactor command functions into command classes
427
    The docstring for an actual command should give a single-line
428
    summary, then a complete description of the command.  A grammar
429
    description will be inserted.
430
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
431
    :cvar aliases: Other accepted names for this command.
432
433
    :cvar takes_args: List of argument forms, marked with whether they are
434
        optional, repeated, etc.  Examples::
435
436
            ['to_location', 'from_branch?', 'file*']
437
438
        * 'to_location' is required
439
        * 'from_branch' is optional
440
        * 'file' can be specified 0 or more times
441
442
    :cvar takes_options: List of options that may be given for this command.
443
        These can be either strings, referring to globally-defined options, or
444
        option objects.  Retrieve through options().
445
446
    :cvar hidden: If true, this command isn't advertised.  This is typically
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
447
        for commands intended for expert users.
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
448
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
449
    :cvar encoding_type: Command objects will get a 'outf' attribute, which has
450
        been setup to properly handle encoding of unicode strings.
451
        encoding_type determines what will happen when characters cannot be
452
        encoded:
453
454
        * strict - abort if we cannot decode
455
        * replace - put in a bogus character (typically '?')
456
        * exact - do not encode sys.stdout
457
458
        NOTE: by default on Windows, sys.stdout is opened as a text stream,
459
        therefore LF line-endings are converted to CRLF.  When a command uses
460
        encoding_type = 'exact', then sys.stdout is forced to be a binary
461
        stream, and line-endings will not mangled.
462
463
    :cvar invoked_as:
5741.3.1 by Martin Pool
Add Command.invoked_as
464
        A string indicating the real name under which this command was
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
465
        invoked, before expansion of aliases.
5741.3.1 by Martin Pool
Add Command.invoked_as
466
        (This may be None if the command was constructed and run in-process.)
467
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
468
    :cvar hooks: An instance of CommandHooks.
5741.3.1 by Martin Pool
Add Command.invoked_as
469
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
470
    :cvar __doc__: The help shown by 'brz help command' for this command.
5264.1.2 by Robert Collins
Final fix for 'no help for command' issue. We now show a clean message
471
        This is set by assigning explicitly to __doc__ so that -OO can
472
        be used::
473
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
474
            class Foo(Command):
475
                __doc__ = "My help goes here"
329 by Martin Pool
- refactor command functions into command classes
476
    """
477
    aliases = []
478
    takes_args = []
479
    takes_options = []
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
480
    encoding_type = 'strict'
5741.3.1 by Martin Pool
Add Command.invoked_as
481
    invoked_as = None
5875.4.6 by INADA Naoki
Call i18n.install in get_help_text.
482
    l10n = True
329 by Martin Pool
- refactor command functions into command classes
483
484
    hidden = False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
485
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
486
    def __init__(self):
487
        """Construct an instance of this command."""
2768.1.4 by Ian Clatworthy
Process --verbose and --quiet standard options
488
        # List of standard options directly supported
489
        self.supported_std_options = []
5141.2.1 by Robert Collins
``bzrlib.commands.Command.run_direct`` is no longer needed - the pre
490
        self._setup_run()
5050.1.3 by Vincent Ladeuil
Delete spurious spaces.
491
4900.1.1 by Andrew Bennetts
Add add_cleanup to Command.
492
    def add_cleanup(self, cleanup_func, *args, **kwargs):
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
493
        """Register a function to call after self.run returns or raises.
494
495
        Functions will be called in LIFO order.
496
        """
4900.1.1 by Andrew Bennetts
Add add_cleanup to Command.
497
        self._operation.add_cleanup(cleanup_func, *args, **kwargs)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
498
499
    def cleanup_now(self):
500
        """Execute and empty pending cleanup functions immediately.
501
502
        After cleanup_now all registered cleanups are forgotten.  add_cleanup
503
        may be called again after cleanup_now; these cleanups will be called
504
        after self.run returns or raises (or when cleanup_now is next called).
505
506
        This is useful for releasing expensive or contentious resources (such
507
        as write locks) before doing further work that does not require those
5141.2.1 by Robert Collins
``bzrlib.commands.Command.run_direct`` is no longer needed - the pre
508
        resources (such as writing results to self.outf). Note though, that
509
        as it releases all resources, this may release locks that the command
510
        wants to hold, so use should be done with care.
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
511
        """
512
        self._operation.cleanup_now()
5050.1.3 by Vincent Ladeuil
Delete spurious spaces.
513
2432.1.12 by Robert Collins
Relocate command help onto Command.
514
    def _usage(self):
515
        """Return single-line grammar for this command.
516
517
        Only describes arguments, not options.
518
        """
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
519
        s = 'brz ' + self.name() + ' '
2432.1.12 by Robert Collins
Relocate command help onto Command.
520
        for aname in self.takes_args:
521
            aname = aname.upper()
522
            if aname[-1] in ['$', '+']:
523
                aname = aname[:-1] + '...'
524
            elif aname[-1] == '?':
525
                aname = '[' + aname[:-1] + ']'
526
            elif aname[-1] == '*':
527
                aname = '[' + aname[:-1] + '...]'
528
            s += aname + ' '
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
529
        s = s[:-1]      # remove last space
2432.1.12 by Robert Collins
Relocate command help onto Command.
530
        return s
531
2677.1.2 by Alexander Belchenko
bzr_man: see also topics as cross-reference links
532
    def get_help_text(self, additional_see_also=None, plain=True,
3984.4.1 by Ian Clatworthy
get_help_text() verbose parameter & keep custom sections ordered
533
                      see_also_as_links=False, verbose=True):
2432.1.21 by Robert Collins
Teach Command.get_help_text to show additional help cross references when supplied.
534
        """Return a text string with help for this command.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
535
2432.1.21 by Robert Collins
Teach Command.get_help_text to show additional help cross references when supplied.
536
        :param additional_see_also: Additional help topics to be
537
            cross-referenced.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
538
        :param plain: if False, raw help (reStructuredText) is
539
            returned instead of plain text.
2677.1.2 by Alexander Belchenko
bzr_man: see also topics as cross-reference links
540
        :param see_also_as_links: if True, convert items in 'See also'
2677.1.4 by Alexander Belchenko
fixes after John's review
541
            list to internal links (used by bzr_man rstx generator)
3984.4.1 by Ian Clatworthy
get_help_text() verbose parameter & keep custom sections ordered
542
        :param verbose: if True, display the full help, otherwise
543
            leave out the descriptive sections and just display
3984.4.8 by Ian Clatworthy
tweak docstring
544
            usage help (e.g. Purpose, Usage, Options) with a
545
            message explaining how to obtain full help.
2432.1.21 by Robert Collins
Teach Command.get_help_text to show additional help cross references when supplied.
546
        """
6112.1.1 by Jonathan Riddell
check for installed i18n before doing install
547
        if self.l10n:
5875.3.25 by Vincent Ladeuil
Fix test failures and make sure we don't rely on a default translation.
548
            i18n.install()  # Install i18n only for get_help_text for now.
2432.1.12 by Robert Collins
Relocate command help onto Command.
549
        doc = self.help()
5875.3.1 by INADA Naoki
Implement command help l10n.
550
        if doc:
5875.4.1 by INADA Naoki
Add comment about describing ":Usage:" section is not translated.
551
            # Note: If self.gettext() translates ':Usage:\n', the section will
552
            # be shown after "Description" section and we don't want to
553
            # translate the usage string.
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
554
            # Though, brz export-pot don't exports :Usage: section and it must
5875.4.1 by INADA Naoki
Add comment about describing ":Usage:" section is not translated.
555
            # not be translated.
5875.3.25 by Vincent Ladeuil
Fix test failures and make sure we don't rely on a default translation.
556
            doc = self.gettext(doc)
5875.3.1 by INADA Naoki
Implement command help l10n.
557
        else:
558
            doc = gettext("No help for this command.")
2432.1.12 by Robert Collins
Relocate command help onto Command.
559
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
560
        # Extract the summary (purpose) and sections out from the text
3974.1.1 by Ian Clatworthy
keep section ordering in help
561
        purpose,sections,order = self._get_help_parts(doc)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
562
563
        # If a custom usage section was provided, use it
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
564
        if 'Usage' in sections:
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
565
            usage = sections.pop('Usage')
566
        else:
567
            usage = self._usage()
568
569
        # The header is the purpose and usage
2432.1.12 by Robert Collins
Relocate command help onto Command.
570
        result = ""
5875.3.26 by Vincent Ladeuil
Tweak test_help some more.
571
        result += gettext(':Purpose: %s\n') % (purpose,)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
572
        if usage.find('\n') >= 0:
5875.3.23 by Vincent Ladeuil
Put the '\n' back into the formats and fix tests accordingly (reducing code duplication).
573
            result += gettext(':Usage:\n%s\n') % (usage,)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
574
        else:
5875.3.23 by Vincent Ladeuil
Put the '\n' back into the formats and fix tests accordingly (reducing code duplication).
575
            result += gettext(':Usage:   %s\n') % (usage,)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
576
        result += '\n'
577
578
        # Add the options
4070.11.3 by Martin Pool
doc
579
        #
580
        # XXX: optparse implicitly rewraps the help, and not always perfectly,
581
        # so we get <https://bugs.launchpad.net/bzr/+bug/249908>.  -- mbp
582
        # 20090319
5875.4.4 by INADA Naoki
Remove l10n of options.
583
        parser = option.get_optparser(self.options())
5875.3.15 by INADA Naoki
Use better variable name.
584
        options = parser.format_option_help()
5860.1.1 by Vincent Ladeuil
Fix some ReST typos in the configuration help and restore the workaround for dotted format names breaking sphinx.
585
        # FIXME: According to the spec, ReST option lists actually don't
586
        # support options like --1.14 so that causes syntax errors (in Sphinx
587
        # at least).  As that pattern always appears in the commands that
588
        # break, we trap on that and then format that block of 'format' options
589
        # as a literal block. We use the most recent format still listed so we
590
        # don't have to do that too often -- vila 20110514
591
        if not plain and options.find('  --1.14  ') != -1:
4634.39.39 by Ian Clatworthy
Fix ReST syntax errors in User Reference caused by options like --1.9 that ReST option lists don't permit
592
            options = options.replace(' format:\n', ' format::\n\n', 1)
5875.3.14 by INADA Naoki
Change how to use gettext for section titles.
593
        if options.startswith('Options:'):
594
            result += gettext(':Options:%s') % (options[len('options:'):],)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
595
        else:
596
            result += options
597
        result += '\n'
598
3984.4.1 by Ian Clatworthy
get_help_text() verbose parameter & keep custom sections ordered
599
        if verbose:
600
            # Add the description, indenting it 2 spaces
601
            # to match the indentation of the options
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
602
            if None in sections:
3984.4.1 by Ian Clatworthy
get_help_text() verbose parameter & keep custom sections ordered
603
                text = sections.pop(None)
604
                text = '\n  '.join(text.splitlines())
5875.3.23 by Vincent Ladeuil
Put the '\n' back into the formats and fix tests accordingly (reducing code duplication).
605
                result += gettext(':Description:\n  %s\n\n') % (text,)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
606
3984.4.1 by Ian Clatworthy
get_help_text() verbose parameter & keep custom sections ordered
607
            # Add the custom sections (e.g. Examples). Note that there's no need
608
            # to indent these as they must be indented already in the source.
609
            if sections:
610
                for label in order:
5875.3.1 by INADA Naoki
Implement command help l10n.
611
                    if label in sections:
612
                        result += ':%s:\n%s\n' % (label, sections[label])
3984.4.1 by Ian Clatworthy
get_help_text() verbose parameter & keep custom sections ordered
613
                result += '\n'
614
        else:
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
615
            result += (gettext("See brz help %s for more details and examples.\n\n")
3984.4.2 by Ian Clatworthy
make help on commands concise by default
616
                % self.name())
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
617
618
        # Add the aliases, source (plug-in) and see also links, if any
2432.1.12 by Robert Collins
Relocate command help onto Command.
619
        if self.aliases:
5875.3.14 by INADA Naoki
Change how to use gettext for section titles.
620
            result += gettext(':Aliases:  ')
2432.1.12 by Robert Collins
Relocate command help onto Command.
621
            result += ', '.join(self.aliases) + '\n'
622
        plugin_name = self.plugin_name()
623
        if plugin_name is not None:
5875.3.14 by INADA Naoki
Change how to use gettext for section titles.
624
            result += gettext(':From:     plugin "%s"\n') % plugin_name
2432.1.21 by Robert Collins
Teach Command.get_help_text to show additional help cross references when supplied.
625
        see_also = self.get_see_also(additional_see_also)
2432.1.12 by Robert Collins
Relocate command help onto Command.
626
        if see_also:
2677.1.4 by Alexander Belchenko
fixes after John's review
627
            if not plain and see_also_as_links:
628
                see_also_links = []
629
                for item in see_also:
630
                    if item == 'topics':
631
                        # topics doesn't have an independent section
632
                        # so don't create a real link
633
                        see_also_links.append(item)
634
                    else:
4927.2.2 by Ian Clatworthy
User Reference as topics
635
                        # Use a Sphinx link for this entry
6147.1.1 by Jonathan Riddell
use .format() instead of % for string formatting where there are multiple formats in one string to allow for translations
636
                        link_text = gettext(":doc:`{0} <{1}-help>`").format(
637
                                                                    item, item)
4927.2.2 by Ian Clatworthy
User Reference as topics
638
                        see_also_links.append(link_text)
2677.1.4 by Alexander Belchenko
fixes after John's review
639
                see_also = see_also_links
5875.3.14 by INADA Naoki
Change how to use gettext for section titles.
640
            result += gettext(':See also: %s') % ', '.join(see_also) + '\n'
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
641
3668.2.1 by Vincent Ladeuil
Fix bug #263249 by setting valid default _param_name.
642
        # If this will be rendered as plain text, convert it
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
643
        if plain:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
644
            import breezy.help_topics
645
            result = breezy.help_topics.help_as_plain_text(result)
2432.1.12 by Robert Collins
Relocate command help onto Command.
646
        return result
647
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
648
    @staticmethod
649
    def _get_help_parts(text):
650
        """Split help text into a summary and named sections.
651
3974.1.1 by Ian Clatworthy
keep section ordering in help
652
        :return: (summary,sections,order) where summary is the top line and
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
653
            sections is a dictionary of the rest indexed by section name.
3974.1.1 by Ian Clatworthy
keep section ordering in help
654
            order is the order the section appear in the text.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
655
            A section starts with a heading line of the form ":xxx:".
656
            Indented text on following lines is the section value.
657
            All text found outside a named section is assigned to the
658
            default section which is given the key of None.
659
        """
3974.1.1 by Ian Clatworthy
keep section ordering in help
660
        def save_section(sections, order, label, section):
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
661
            if len(section) > 0:
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
662
                if label in sections:
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
663
                    sections[label] += '\n' + section
664
                else:
3974.1.1 by Ian Clatworthy
keep section ordering in help
665
                    order.append(label)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
666
                    sections[label] = section
3668.2.1 by Vincent Ladeuil
Fix bug #263249 by setting valid default _param_name.
667
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
668
        lines = text.rstrip().splitlines()
669
        summary = lines.pop(0)
670
        sections = {}
3974.1.1 by Ian Clatworthy
keep section ordering in help
671
        order = []
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
672
        label,section = None,''
673
        for line in lines:
674
            if line.startswith(':') and line.endswith(':') and len(line) > 2:
3974.1.1 by Ian Clatworthy
keep section ordering in help
675
                save_section(sections, order, label, section)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
676
                label,section = line[1:-1],''
3376.2.11 by Martin Pool
Compare to None using is/is not not ==
677
            elif (label is not None) and len(line) > 1 and not line[0].isspace():
3974.1.1 by Ian Clatworthy
keep section ordering in help
678
                save_section(sections, order, label, section)
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
679
                label,section = None,line
680
            else:
681
                if len(section) > 0:
682
                    section += '\n' + line
683
                else:
684
                    section = line
3974.1.1 by Ian Clatworthy
keep section ordering in help
685
        save_section(sections, order, label, section)
686
        return summary, sections, order
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
687
2432.1.28 by Robert Collins
Add a get_help_topic method to commands.Command.
688
    def get_help_topic(self):
689
        """Return the commands help topic - its name."""
690
        return self.name()
691
2432.1.21 by Robert Collins
Teach Command.get_help_text to show additional help cross references when supplied.
692
    def get_see_also(self, additional_terms=None):
2677.1.2 by Alexander Belchenko
bzr_man: see also topics as cross-reference links
693
        """Return a list of help topics that are related to this command.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
694
2425.2.1 by Robert Collins
Command objects can now declare related help topics by having _see_also
695
        The list is derived from the content of the _see_also attribute. Any
696
        duplicates are removed and the result is in lexical order.
2432.1.21 by Robert Collins
Teach Command.get_help_text to show additional help cross references when supplied.
697
        :param additional_terms: Additional help topics to cross-reference.
2425.2.1 by Robert Collins
Command objects can now declare related help topics by having _see_also
698
        :return: A list of help topics.
699
        """
2432.1.21 by Robert Collins
Teach Command.get_help_text to show additional help cross references when supplied.
700
        see_also = set(getattr(self, '_see_also', []))
701
        if additional_terms:
702
            see_also.update(additional_terms)
703
        return sorted(see_also)
2425.2.1 by Robert Collins
Command objects can now declare related help topics by having _see_also
704
1185.16.43 by Martin Pool
- clean up handling of option objects
705
    def options(self):
706
        """Return dict of valid options for this command.
707
708
        Maps from long option name to option object."""
2768.1.4 by Ian Clatworthy
Process --verbose and --quiet standard options
709
        r = Option.STD_OPTIONS.copy()
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
710
        std_names = set(r)
1185.16.43 by Martin Pool
- clean up handling of option objects
711
        for o in self.takes_options:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
712
            if isinstance(o, string_types):
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
713
                o = option.Option.OPTIONS[o]
1185.16.43 by Martin Pool
- clean up handling of option objects
714
            r[o.name] = o
2768.1.4 by Ian Clatworthy
Process --verbose and --quiet standard options
715
            if o.name in std_names:
716
                self.supported_std_options.append(o.name)
1185.16.43 by Martin Pool
- clean up handling of option objects
717
        return r
1165 by Martin Pool
- move parsing of argv into arguments and options into Command.run_argv
718
1685.1.80 by Wouter van Heyst
more code cleanup
719
    def _setup_outf(self):
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
720
        """Return a file linked to stdout, which has proper encoding."""
4792.8.9 by Martin Pool
Send Command.outf through UIFactory
721
        self.outf = ui.ui_factory.make_output_stream(
722
            encoding_type=self.encoding_type)
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
723
1581.1.1 by Robert Collins
Bugfix aliases to be backwards compatible with plugins providing command.run_argv.
724
    def run_argv_aliases(self, argv, alias_argv=None):
725
        """Parse the command line and run with extra aliases in alias_argv."""
1553.6.8 by Erik Bågfors
support for overrides
726
        args, opts = parse_args(self, argv, alias_argv)
5875.4.2 by INADA Naoki
Command.run_argv_aliases() always calls self._setup_outf.
727
        self._setup_outf()
2768.1.4 by Ian Clatworthy
Process --verbose and --quiet standard options
728
729
        # Process the standard options
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
730
        if 'help' in opts:  # e.g. brz add --help
5875.3.1 by INADA Naoki
Implement command help l10n.
731
            self.outf.write(self.get_help_text())
3984.4.6 by Ian Clatworthy
Show usage on --usage, not -h
732
            return 0
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
733
        if 'usage' in opts:  # e.g. brz add --usage
5875.3.16 by INADA Naoki
Use _outf for '--using' too.
734
            self.outf.write(self.get_help_text(verbose=False))
3984.4.5 by Ian Clatworthy
help xxx is full help; xxx -h is concise help
735
            return 0
2768.1.4 by Ian Clatworthy
Process --verbose and --quiet standard options
736
        trace.set_verbosity_level(option._verbosity_level)
737
        if 'verbose' in self.supported_std_options:
738
            opts['verbose'] = trace.is_verbose()
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
739
        elif 'verbose' in opts:
2768.1.4 by Ian Clatworthy
Process --verbose and --quiet standard options
740
            del opts['verbose']
741
        if 'quiet' in self.supported_std_options:
742
            opts['quiet'] = trace.is_quiet()
6619.3.1 by Jelmer Vernooij
Apply 2to3 has_key fix.
743
        elif 'quiet' in opts:
2768.1.4 by Ian Clatworthy
Process --verbose and --quiet standard options
744
            del opts['quiet']
1165 by Martin Pool
- move parsing of argv into arguments and options into Command.run_argv
745
        # mix arguments and options into one dictionary
746
        cmdargs = _match_argform(self.name(), self.takes_args, args)
747
        cmdopts = {}
748
        for k, v in opts.items():
749
            cmdopts[k.replace('-', '_')] = v
750
751
        all_cmd_args = cmdargs.copy()
752
        all_cmd_args.update(cmdopts)
753
5463.1.2 by Martin Pool
Make run_argv_aliases reset the global verbosity after running
754
        try:
755
            return self.run(**all_cmd_args)
756
        finally:
757
            # reset it, so that other commands run in the same process won't
5609.16.1 by John Arbash Meinel
Fix bug #713258. Restore logging of bytes transferred.
758
            # inherit state. Before we reset it, log any activity, so that it
759
            # gets properly tracked.
760
            ui.ui_factory.log_transport_activity(
761
                display=('bytes' in debug.debug_flags))
5463.1.2 by Martin Pool
Make run_argv_aliases reset the global verbosity after running
762
            trace.set_verbosity_level(0)
5141.2.1 by Robert Collins
``bzrlib.commands.Command.run_direct`` is no longer needed - the pre
763
764
    def _setup_run(self):
765
        """Wrap the defined run method on self with a cleanup.
766
767
        This is called by __init__ to make the Command be able to be run
768
        by just calling run(), as it could be before cleanups were added.
769
770
        If a different form of cleanups are in use by your Command subclass,
771
        you can override this method.
772
        """
773
        class_run = self.run
774
        def run(*args, **kwargs):
6240.5.7 by Jelmer Vernooij
Drop exception suppression support.
775
            for hook in Command.hooks['pre_command']:
776
                hook(self)
5141.2.1 by Robert Collins
``bzrlib.commands.Command.run_direct`` is no longer needed - the pre
777
            self._operation = cleanup.OperationWithCleanups(class_run)
778
            try:
779
                return self._operation.run_simple(*args, **kwargs)
780
            finally:
781
                del self._operation
6240.5.7 by Jelmer Vernooij
Drop exception suppression support.
782
                for hook in Command.hooks['post_command']:
783
                    hook(self)
5141.2.1 by Robert Collins
``bzrlib.commands.Command.run_direct`` is no longer needed - the pre
784
        self.run = run
785
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
786
    def run(self):
787
        """Actually run the command.
329 by Martin Pool
- refactor command functions into command classes
788
789
        This is invoked with the options and arguments bound to
790
        keyword parameters.
791
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
792
        Return 0 or None if the command was successful, or a non-zero
793
        shell error code if not.  It's OK for this method to allow
794
        an exception to raise up.
5141.2.1 by Robert Collins
``bzrlib.commands.Command.run_direct`` is no longer needed - the pre
795
796
        This method is automatically wrapped by Command.__init__ with a 
797
        cleanup operation, stored as self._operation. This can be used
798
        via self.add_cleanup to perform automatic cleanups at the end of
799
        run().
800
801
        The argument for run are assembled by introspection. So for instance,
802
        if your command takes an argument files, you would declare::
803
804
            def run(self, files=None):
805
                pass
329 by Martin Pool
- refactor command functions into command classes
806
        """
2155.2.1 by Marius Kruger
* Get command aliases to respect quoted arguments.
807
        raise NotImplementedError('no implementation of command %r'
1610.1.3 by Martin Pool
Better error message for Command.run() not implemented
808
                                  % self.name())
329 by Martin Pool
- refactor command functions into command classes
809
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
810
    def help(self):
811
        """Return help message for this class."""
1610.1.2 by Martin Pool
Move rarely-used import into Command.help()
812
        from inspect import getdoc
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
813
        if self.__doc__ is Command.__doc__:
814
            return None
815
        return getdoc(self)
816
5875.4.3 by INADA Naoki
Don't use property
817
    def gettext(self, message):
5875.3.1 by INADA Naoki
Implement command help l10n.
818
        """Returns the gettext function used to translate this command's help.
819
5875.3.18 by INADA Naoki
Fix docstring of Command.get_gettext
820
        Commands provided by plugins should override this to use their
821
        own i18n system.
5875.3.1 by INADA Naoki
Implement command help l10n.
822
        """
5875.3.25 by Vincent Ladeuil
Fix test failures and make sure we don't rely on a default translation.
823
        return i18n.gettext_per_paragraph(message)
5875.3.1 by INADA Naoki
Implement command help l10n.
824
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
825
    def name(self):
5741.3.1 by Martin Pool
Add Command.invoked_as
826
        """Return the canonical name for this command.
827
828
        The name under which it was actually invoked is available in invoked_as.
829
        """
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
830
        return _unsquish_command_name(self.__class__.__name__)
831
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
832
    def plugin_name(self):
833
        """Get the name of the plugin that provides this command.
834
835
        :return: The name of the plugin or None if the command is builtin.
836
        """
6651.4.2 by Martin
Move plugin_name logic from commands to plugin to fix test
837
        return plugin_name(self.__module__)
1733.2.5 by Michael Ellerman
Show which plugin (if any) provides a command.
838
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
839
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
840
class CommandHooks(Hooks):
841
    """Hooks related to Command object creation/enumeration."""
842
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
843
    def __init__(self):
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
844
        """Create the default hooks.
845
846
        These are all empty initially, because by default nothing should get
847
        notified.
848
        """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
849
        Hooks.__init__(self, "breezy.commands", "Command.hooks")
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
850
        self.add_hook('extend_command',
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
851
            "Called after creating a command object to allow modifications "
852
            "such as adding or removing options, docs etc. Called with the "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
853
            "new breezy.commands.Command object.", (1, 13))
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
854
        self.add_hook('get_command',
4119.3.4 by Robert Collins
Add Command lookup hooks: list_commands and get_command.
855
            "Called when creating a single command. Called with "
856
            "(cmd_or_None, command_name). get_command should either return "
857
            "the cmd_or_None parameter, or a replacement Command object that "
4119.3.10 by Robert Collins
More review feedback.
858
            "should be used for the command. Note that the Command.hooks "
859
            "hooks are core infrastructure. Many users will prefer to use "
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
860
            "breezy.commands.register_command or plugin_cmds.register_lazy.",
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
861
            (1, 17))
862
        self.add_hook('get_missing_command',
4119.3.8 by Robert Collins
Get missing command support sorted out.
863
            "Called when creating a single command if no command could be "
864
            "found. Called with (command_name). get_missing_command should "
865
            "either return None, or a Command object to be used for the "
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
866
            "command.", (1, 17))
867
        self.add_hook('list_commands',
4119.3.10 by Robert Collins
More review feedback.
868
            "Called when enumerating commands. Called with a set of "
869
            "cmd_name strings for all the commands found so far. This set "
870
            " is safe to mutate - e.g. to remove a command. "
871
            "list_commands should return the updated set of command names.",
5622.3.2 by Jelmer Vernooij
Add more lazily usable hook points.
872
            (1, 17))
6240.5.1 by Brian de Alwis
Introduce two new command hooks, 'pre_command' and 'post_command',
873
        self.add_hook('pre_command',
874
            "Called prior to executing a command. Called with the command "
6475.1.1 by Brian de Alwis
Doc fix: command hooks available in 2.6
875
            "object.", (2, 6))
6240.5.1 by Brian de Alwis
Introduce two new command hooks, 'pre_command' and 'post_command',
876
        self.add_hook('post_command',
877
            "Called after executing a command. Called with the command "
6475.1.1 by Brian de Alwis
Doc fix: command hooks available in 2.6
878
            "object.", (2, 6))
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
879
5622.3.10 by Jelmer Vernooij
Don't require arguments to hooks.
880
Command.hooks = CommandHooks()
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
881
882
1553.6.11 by Erik Bågfors
small bugfixes, all tests pass now
883
def parse_args(command, argv, alias_argv=None):
1 by mbp at sourcefrog
import from baz patch-364
884
    """Parse command line.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
885
1 by mbp at sourcefrog
import from baz patch-364
886
    Arguments and options are parsed at this level before being passed
887
    down to specific command handlers.  This routine knows, from a
888
    lookup table, something about the available options, what optargs
889
    they take, and which commands will accept them.
890
    """
1857.1.1 by Aaron Bentley
Use optparse for parsing options
891
    # TODO: make it a method of the Command?
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
892
    parser = option.get_optparser(command.options())
1857.1.1 by Aaron Bentley
Use optparse for parsing options
893
    if alias_argv is not None:
894
        args = alias_argv + argv
895
    else:
896
        args = argv
683 by Martin Pool
- short option stacking patch from John A Meinel
897
5514.3.2 by Rory Yorke
Added comment on try-except around pargse_args(), w/ pointer to Python bug.
898
    # for python 2.5 and later, optparse raises this exception if a non-ascii
899
    # option name is given.  See http://bugs.python.org/issue2931
5514.3.1 by Rory Yorke
Report an error if a non-ASCII option name is given (bug 140563).
900
    try:
901
        options, args = parser.parse_args(args)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
902
    except UnicodeEncodeError as e:
6171.2.1 by Vincent Ladeuil
Global options respect their hidden attribute
903
        raise errors.BzrCommandError(
904
            gettext('Only ASCII permitted in option names'))
5514.3.1 by Rory Yorke
Report an error if a non-ASCII option name is given (bug 140563).
905
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
906
    opts = dict((k, v) for k, v in options.__dict__.items() if
907
                v is not option.OptionParser.DEFAULT_VALUE)
1 by mbp at sourcefrog
import from baz patch-364
908
    return args, opts
909
910
329 by Martin Pool
- refactor command functions into command classes
911
def _match_argform(cmd, takes_args, args):
1 by mbp at sourcefrog
import from baz patch-364
912
    argdict = {}
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
913
329 by Martin Pool
- refactor command functions into command classes
914
    # step through args and takes_args, allowing appropriate 0-many matches
915
    for ap in takes_args:
1 by mbp at sourcefrog
import from baz patch-364
916
        argname = ap[:-1]
917
        if ap[-1] == '?':
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
918
            if args:
919
                argdict[argname] = args.pop(0)
196 by mbp at sourcefrog
selected-file diff
920
        elif ap[-1] == '*': # all remaining arguments
921
            if args:
922
                argdict[argname + '_list'] = args[:]
923
                args = []
924
            else:
925
                argdict[argname + '_list'] = None
1 by mbp at sourcefrog
import from baz patch-364
926
        elif ap[-1] == '+':
927
            if not args:
6138.3.7 by Jonathan Riddell
add gettext() to BzrCommandError uses
928
                raise errors.BzrCommandError(gettext(
929
                      "command {0!r} needs one or more {1}").format(
930
                      cmd, argname.upper()))
1 by mbp at sourcefrog
import from baz patch-364
931
            else:
932
                argdict[argname + '_list'] = args[:]
933
                args = []
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
934
        elif ap[-1] == '$': # all but one
935
            if len(args) < 2:
6138.3.7 by Jonathan Riddell
add gettext() to BzrCommandError uses
936
                raise errors.BzrCommandError(
937
                      gettext("command {0!r} needs one or more {1}").format(
938
                                             cmd, argname.upper()))
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
939
            argdict[argname + '_list'] = args[:-1]
1740.5.6 by Martin Pool
Clean up many exception classes.
940
            args[:-1] = []
1 by mbp at sourcefrog
import from baz patch-364
941
        else:
942
            # just a plain arg
943
            argname = ap
944
            if not args:
6138.3.7 by Jonathan Riddell
add gettext() to BzrCommandError uses
945
                raise errors.BzrCommandError(
946
                     gettext("command {0!r} requires argument {1}").format(
947
                               cmd, argname.upper()))
1 by mbp at sourcefrog
import from baz patch-364
948
            else:
949
                argdict[argname] = args.pop(0)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
950
1 by mbp at sourcefrog
import from baz patch-364
951
    if args:
6138.3.14 by Jonathan Riddell
fix syntax
952
        raise errors.BzrCommandError( gettext(
953
                              "extra argument to command {0}: {1}").format(
954
                                       cmd, args[0]) )
1 by mbp at sourcefrog
import from baz patch-364
955
956
    return argdict
957
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
958
def apply_coveraged(dirname, the_callable, *args, **kwargs):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
959
    # Cannot use "import trace", as that would import breezy.trace instead of
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
960
    # the standard library's trace.
961
    trace = __import__('trace')
962
963
    tracer = trace.Trace(count=1, trace=0)
964
    sys.settrace(tracer.globaltrace)
4325.1.1 by Vincent Ladeuil
Make --coverage works for threads too.
965
    threading.settrace(tracer.globaltrace)
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
966
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
967
    try:
968
        return exception_to_return_code(the_callable, *args, **kwargs)
969
    finally:
970
        sys.settrace(None)
971
        results = tracer.results()
972
        results.write_results(show_missing=1, summary=False,
973
                              coverdir=dirname)
1 by mbp at sourcefrog
import from baz patch-364
974
975
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
976
def apply_profiled(the_callable, *args, **kwargs):
977
    import hotshot
978
    import tempfile
1393.1.27 by Martin Pool
- clean up profile code and change default sort order
979
    import hotshot.stats
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
980
    pffileno, pfname = tempfile.mkstemp()
981
    try:
982
        prof = hotshot.Profile(pfname)
983
        try:
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
984
            ret = prof.runcall(exception_to_return_code, the_callable, *args,
985
                **kwargs) or 0
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
986
        finally:
987
            prof.close()
988
        stats = hotshot.stats.load(pfname)
1393.1.27 by Martin Pool
- clean up profile code and change default sort order
989
        stats.strip_dirs()
990
        stats.sort_stats('cum')   # 'time'
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
991
        ## XXX: Might like to write to stderr or the trace file instead but
992
        ## print_stats seems hardcoded to stdout
993
        stats.print_stats(20)
994
        return ret
995
    finally:
996
        os.close(pffileno)
997
        os.remove(pfname)
998
999
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1000
def exception_to_return_code(the_callable, *args, **kwargs):
1001
    """UI level helper for profiling and coverage.
1002
4084.6.3 by Robert Collins
Disagreement on trailing whitespace with the test suite.
1003
    This transforms exceptions into a return value of 3. As such its only
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1004
    relevant to the UI layer, and should never be called where catching
1005
    exceptions may be desirable.
1006
    """
1007
    try:
1008
        return the_callable(*args, **kwargs)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1009
    except (KeyboardInterrupt, Exception) as e:
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1010
        # used to handle AssertionError and KeyboardInterrupt
1011
        # specially here, but hopefully they're handled ok by the logger now
1012
        exc_info = sys.exc_info()
1013
        exitcode = trace.report_exception(exc_info, sys.stderr)
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1014
        if os.environ.get('BRZ_PDB'):
6619.3.3 by Jelmer Vernooij
Apply 2to3 print fix.
1015
            print('**** entering debugger')
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1016
            import pdb
6555.1.2 by Jelmer Vernooij
Inline traceback specification.
1017
            pdb.post_mortem(exc_info[2])
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1018
        return exitcode
1019
1020
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1021
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1022
    from breezy.lsprof import profile
6027.1.3 by Vincent Ladeuil
Remove bzrlib.commands deprecated stuff.
1023
    ret, stats = profile(exception_to_return_code, the_callable,
1024
                         *args, **kwargs)
1185.33.85 by Martin Pool
New --lsprof option from Denys Duchier
1025
    stats.sort()
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1026
    if filename is None:
1027
        stats.pprint()
1028
    else:
2654.2.2 by Ian Clatworthy
Put all format detection stuff in one spot as requested by John Arbash Meinel
1029
        stats.save(filename)
6138.3.2 by Jonathan Riddell
gettext-ify bzrlib/commit.py
1030
        trace.note(gettext('Profile data written to "%s".'), filename)
1185.33.85 by Martin Pool
New --lsprof option from Denys Duchier
1031
    return ret
1032
1553.6.9 by Erik Bågfors
PEP8-ify
1033
2155.2.1 by Marius Kruger
* Get command aliases to respect quoted arguments.
1034
def get_alias(cmd, config=None):
1035
    """Return an expanded alias, or None if no alias exists.
1036
1037
    cmd
1038
        Command to be checked for an alias.
1039
    config
1040
        Used to specify an alternative config to use,
2155.2.3 by Marius Kruger
* commands.py
1041
        which is especially useful for testing.
2155.2.1 by Marius Kruger
* Get command aliases to respect quoted arguments.
1042
        If it is unspecified, the global config will be used.
1043
    """
1044
    if config is None:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1045
        import breezy.config
1046
        config = breezy.config.GlobalConfig()
2155.2.1 by Marius Kruger
* Get command aliases to respect quoted arguments.
1047
    alias = config.get_alias(cmd)
1553.6.1 by Erik Bågfors
support for aliases in bazaar.conf
1048
    if (alias):
4913.5.24 by Gordon Tyler
Added cmdline.split function, which replaces commands.shlex_split_unicode.
1049
        return cmdline.split(alias)
1553.6.8 by Erik Bågfors
support for overrides
1050
    return None
1553.6.1 by Erik Bågfors
support for aliases in bazaar.conf
1051
1553.6.9 by Erik Bågfors
PEP8-ify
1052
5051.1.1 by Robert Collins
* ``bzrlib.comands.run_bzr`` is more extensible: callers can supply the
1053
def run_bzr(argv, load_plugins=load_plugins, disable_plugins=disable_plugins):
1 by mbp at sourcefrog
import from baz patch-364
1054
    """Execute a command.
1055
5051.1.1 by Robert Collins
* ``bzrlib.comands.run_bzr`` is more extensible: callers can supply the
1056
    :param argv: The command-line arguments, without the program name from
1057
        argv[0] These should already be decoded. All library/test code calling
1058
        run_bzr should be passing valid strings (don't need decoding).
1059
    :param load_plugins: What function to call when triggering plugin loading.
1060
        This function should take no arguments and cause all plugins to be
1061
        loaded.
1062
    :param disable_plugins: What function to call when disabling plugin
1063
        loading. This function should take no arguments and cause all plugin
1064
        loading to be prohibited (so that code paths in your application that
1065
        know about some plugins possibly being present will fail to import
1066
        those plugins even if they are installed.)
1067
    :return: Returns a command exit code or raises an exception.
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1068
1069
    Special master options: these must come before the command because
1070
    they control how the command is interpreted.
1071
1072
    --no-plugins
1073
        Do not load plugin modules at all
1074
1553.6.1 by Erik Bågfors
support for aliases in bazaar.conf
1075
    --no-aliases
1076
        Do not allow aliases
1077
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1078
    --builtin
1079
        Only use builtin commands.  (Plugins are still allowed to change
1080
        other behaviour.)
1081
1082
    --profile
1185.33.85 by Martin Pool
New --lsprof option from Denys Duchier
1083
        Run under the Python hotshot profiler.
1084
1085
    --lsprof
1086
        Run under the Python lsprof profiler.
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
1087
1088
    --coverage
1089
        Generate line coverage report in the specified directory.
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
1090
1091
    --concurrency
4766.3.9 by Vincent Ladeuil
Make it clear that --concurrency is for selftest only (so far).
1092
        Specify the number of processes that can be run concurrently (selftest).
1 by mbp at sourcefrog
import from baz patch-364
1093
    """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1094
    trace.mutter("breezy version: " + breezy.__version__)
5785.1.2 by Martin
Move _specified_or_unicode_argv call inside run_bzr as it may raise an error that should be reported
1095
    argv = _specified_or_unicode_argv(argv)
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
1096
    trace.mutter("brz arguments: %r", argv)
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
1097
5875.3.1 by INADA Naoki
Implement command help l10n.
1098
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = \
5875.3.22 by INADA Naoki
s/i18n/l10n/
1099
            opt_no_l10n = opt_no_aliases = False
4766.3.7 by Vincent Ladeuil
Mix BZR_CONCURRENCY and --concurrency so both are available.
1100
    opt_lsprof_file = opt_coverage_dir = None
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1101
1102
    # --no-plugins is handled specially at a very early stage. We need
1103
    # to load plugins before doing other command parsing so that they
1104
    # can override commands, but this needs to happen first.
1105
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1106
    argv_copy = []
1107
    i = 0
6161.1.4 by Vincent Ladeuil
Follow the lead of other 'global' options which are not declared in option.py but handled in bzrlib.commands.run_bzr instead.
1108
    override_config = []
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1109
    while i < len(argv):
1110
        a = argv[i]
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1111
        if a == '--profile':
1112
            opt_profile = True
1185.33.85 by Martin Pool
New --lsprof option from Denys Duchier
1113
        elif a == '--lsprof':
1114
            opt_lsprof = True
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1115
        elif a == '--lsprof-file':
1706.2.6 by Robey Pointer
when giving --lsprof-file, assume --lsprof
1116
            opt_lsprof = True
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1117
            opt_lsprof_file = argv[i + 1]
1118
            i += 1
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1119
        elif a == '--no-plugins':
1120
            opt_no_plugins = True
1553.6.1 by Erik Bågfors
support for aliases in bazaar.conf
1121
        elif a == '--no-aliases':
1122
            opt_no_aliases = True
5875.3.22 by INADA Naoki
s/i18n/l10n/
1123
        elif a == '--no-l10n':
1124
            opt_no_l10n = True
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1125
        elif a == '--builtin':
1126
            opt_builtin = True
4766.3.4 by Matt Nordhoff
Change the environment variable to a global option.
1127
        elif a == '--concurrency':
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1128
            os.environ['BRZ_CONCURRENCY'] = argv[i + 1]
4766.3.4 by Matt Nordhoff
Change the environment variable to a global option.
1129
            i += 1
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
1130
        elif a == '--coverage':
1131
            opt_coverage_dir = argv[i + 1]
1132
            i += 1
5274.4.10 by Jason Spashett
Take away removal of --profile-imports from bzr script. Instead ignore this in global options bzrlib/commands.py run_bzr
1133
        elif a == '--profile-imports':
1134
            pass # already handled in startup script Bug #588277
2095.5.1 by Martin Pool
Add new -Derror global option to always display tracebacks
1135
        elif a.startswith('-D'):
2095.5.2 by Martin Pool
save commit message if commit fails (#32054)
1136
            debug.debug_flags.add(a[2:])
6161.1.4 by Vincent Ladeuil
Follow the lead of other 'global' options which are not declared in option.py but handled in bzrlib.commands.run_bzr instead.
1137
        elif a.startswith('-O'):
1138
            override_config.append(a[2:])
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1139
        else:
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1140
            argv_copy.append(a)
1141
        i += 1
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1142
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1143
    if breezy.global_state is None:
1144
        # FIXME: Workaround for users that imported breezy but didn't call
1145
        # breezy.initialize -- vila 2012-01-19
6437.6.1 by Vincent Ladeuil
Support scripts that don't call bzrlib.initialize() but still call run_bzr().
1146
        cmdline_overrides = config.CommandLineStore()
1147
    else:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1148
        cmdline_overrides = breezy.global_state.cmdline_overrides
6437.6.1 by Vincent Ladeuil
Support scripts that don't call bzrlib.initialize() but still call run_bzr().
1149
    cmdline_overrides._from_cmdline(override_config)
6161.1.4 by Vincent Ladeuil
Follow the lead of other 'global' options which are not declared in option.py but handled in bzrlib.commands.run_bzr instead.
1150
4070.8.2 by Martin Pool
Initial support for debug_flags config option
1151
    debug.set_debug_flags_from_config()
1152
5051.1.1 by Robert Collins
* ``bzrlib.comands.run_bzr`` is more extensible: callers can supply the
1153
    if not opt_no_plugins:
1154
        load_plugins()
1155
    else:
1156
        disable_plugins()
1157
1553.7.1 by Robey Pointer
add --lsprof-file option to specify a file for writing lsprof data to (instead of dumping a pretty-print to the terminal)
1158
    argv = argv_copy
1616.1.15 by Martin Pool
Handle 'bzr ?', etc.
1159
    if (not argv):
5051.1.1 by Robert Collins
* ``bzrlib.comands.run_bzr`` is more extensible: callers can supply the
1160
        get_cmd_object('help').run_argv_aliases([])
1165 by Martin Pool
- move parsing of argv into arguments and options into Command.run_argv
1161
        return 0
1162
1163
    if argv[0] == '--version':
5051.1.1 by Robert Collins
* ``bzrlib.comands.run_bzr`` is more extensible: callers can supply the
1164
        get_cmd_object('version').run_argv_aliases([])
1165 by Martin Pool
- move parsing of argv into arguments and options into Command.run_argv
1165
        return 0
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
1166
1553.6.17 by Erik Bågfors
fix for broken --no-aliases
1167
    alias_argv = None
1168
1553.6.1 by Erik Bågfors
support for aliases in bazaar.conf
1169
    if not opt_no_aliases:
1553.6.8 by Erik Bågfors
support for overrides
1170
        alias_argv = get_alias(argv[0])
1171
        if alias_argv:
1172
            argv[0] = alias_argv.pop(0)
1553.6.1 by Erik Bågfors
support for aliases in bazaar.conf
1173
1948.1.1 by John Arbash Meinel
Raise a reasonable error when a command is non-ascii
1174
    cmd = argv.pop(0)
1162 by Martin Pool
- change Command infrastructure to use (mostly stateless) objects to
1175
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
5875.4.6 by INADA Naoki
Call i18n.install in get_help_text.
1176
    if opt_no_l10n:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
1177
        cmd_obj.l10n = False
2367.2.1 by Robert Collins
Remove bzrlib 0.8 compatability where it was making the code unclear or messy. (Robert Collins)
1178
    run = cmd_obj.run_argv_aliases
1179
    run_argv = [argv, alias_argv]
1534.7.154 by Aaron Bentley
Removed changes from bzr.ab 1529..1536
1180
1185.33.42 by Martin Pool
[patch] make --quiet a global option (robey)
1181
    try:
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
1182
        # We can be called recursively (tests for example), but we don't want
1183
        # the verbosity level to propagate.
1184
        saved_verbosity_level = option._verbosity_level
1185
        option._verbosity_level = 0
1185.33.85 by Martin Pool
New --lsprof option from Denys Duchier
1186
        if opt_lsprof:
3169.3.4 by Andrew Bennetts
Warn if --coverage is used with a conflicting global option.
1187
            if opt_coverage_dir:
1188
                trace.warning(
1189
                    '--coverage ignored, because --lsprof is in use.')
1581.1.1 by Robert Collins
Bugfix aliases to be backwards compatible with plugins providing command.run_argv.
1190
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
1185.33.85 by Martin Pool
New --lsprof option from Denys Duchier
1191
        elif opt_profile:
3169.3.4 by Andrew Bennetts
Warn if --coverage is used with a conflicting global option.
1192
            if opt_coverage_dir:
1193
                trace.warning(
1194
                    '--coverage ignored, because --profile is in use.')
1581.1.1 by Robert Collins
Bugfix aliases to be backwards compatible with plugins providing command.run_argv.
1195
            ret = apply_profiled(run, *run_argv)
3169.3.1 by Andrew Bennetts
Make --coverage a global option.
1196
        elif opt_coverage_dir:
1197
            ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
1185.33.42 by Martin Pool
[patch] make --quiet a global option (robey)
1198
        else:
1581.1.1 by Robert Collins
Bugfix aliases to be backwards compatible with plugins providing command.run_argv.
1199
            ret = run(*run_argv)
1185.33.42 by Martin Pool
[patch] make --quiet a global option (robey)
1200
        return ret or 0
1201
    finally:
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
1202
        # reset, in case we may do other commands later within the same
1203
        # process. Commands that want to execute sub-commands must propagate
1204
        # --verbose in their own way.
4682.1.1 by John Arbash Meinel
Put the 'debug_memory' check into the finally clause.
1205
        if 'memory' in debug.debug_flags:
1206
            trace.debug_memory('Process status after command:', short=False)
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
1207
        option._verbosity_level = saved_verbosity_level
6161.1.5 by Vincent Ladeuil
Get rid of the --override-config long name, ensures the overrides are resest when the command has run.
1208
        # Reset the overrides 
6437.6.1 by Vincent Ladeuil
Support scripts that don't call bzrlib.initialize() but still call run_bzr().
1209
        cmdline_overrides._reset()
267 by Martin Pool
- better reporting of errors
1210
4000.1.1 by Robert Collins
Add a new hook Commands['extend_command'] for plugins that want to alter commands without overriding the entire command.
1211
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1212
def display_command(func):
1185.33.18 by Martin Pool
[patch] handle bad IOError subclass raised by urlopen
1213
    """Decorator that suppresses pipe/interrupt errors."""
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1214
    def ignore_pipe(*args, **kwargs):
1215
        try:
1185.35.22 by Aaron Bentley
Handled more pipe errors for display commands.
1216
            result = func(*args, **kwargs)
1217
            sys.stdout.flush()
1218
            return result
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1219
        except IOError as e:
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1220
            if getattr(e, 'errno', None) is None:
1185.33.18 by Martin Pool
[patch] handle bad IOError subclass raised by urlopen
1221
                raise
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1222
            if e.errno != errno.EPIPE:
1711.4.31 by John Arbash Meinel
Catch proper error instead of EPIPE on win32, also don't double flush
1223
                # Win32 raises IOError with errno=0 on a broken pipe
2304.2.1 by Alexander Belchenko
Suppress IOError with errno=22 (Invalid argument) on win32 when pipe is broken
1224
                if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
1711.4.31 by John Arbash Meinel
Catch proper error instead of EPIPE on win32, also don't double flush
1225
                    raise
1185.33.18 by Martin Pool
[patch] handle bad IOError subclass raised by urlopen
1226
            pass
1185.12.69 by Aaron Bentley
Ignored ^C in display commands
1227
        except KeyboardInterrupt:
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1228
            pass
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1229
    return ignore_pipe
267 by Martin Pool
- better reporting of errors
1230
1185.43.6 by Martin Pool
Enable logging early enough to save argv
1231
4119.3.8 by Robert Collins
Get missing command support sorted out.
1232
def install_bzr_command_hooks():
1233
    """Install the hooks to supply bzr's own commands."""
4119.3.13 by Robert Collins
Unbreak blackbox tests.
1234
    if _list_bzr_commands in Command.hooks["list_commands"]:
1235
        return
4119.3.8 by Robert Collins
Get missing command support sorted out.
1236
    Command.hooks.install_named_hook("list_commands", _list_bzr_commands,
1237
        "bzr commands")
1238
    Command.hooks.install_named_hook("get_command", _get_bzr_command,
1239
        "bzr commands")
1240
    Command.hooks.install_named_hook("get_command", _get_plugin_command,
1241
        "bzr plugin commands")
1242
    Command.hooks.install_named_hook("get_command", _get_external_command,
1243
        "bzr external command lookup")
6161.1.1 by Vincent Ladeuil
Allow config options to be overridden from the command line
1244
    Command.hooks.install_named_hook("get_missing_command",
1245
                                     _try_plugin_provider,
1246
                                     "bzr plugin-provider-db check")
4119.3.8 by Robert Collins
Get missing command support sorted out.
1247
1248
5017.1.1 by Martin Pool
Add bzrlib.initialize
1249
1250
def _specified_or_unicode_argv(argv):
1251
    # For internal or testing use, argv can be passed.  Otherwise, get it from
1252
    # the process arguments in a unicode-safe way.
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
1253
    if argv is None:
5274.4.8 by Jason Spashett
Reverse merge -r 5280..5279
1254
        return osutils.get_unicode_argv()
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
1255
    else:
4355.2.3 by Alexander Belchenko
commands.py: main() function expect to get argv argument as list of unicode or pure ascii strings.
1256
        new_argv = []
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
1257
        try:
4355.2.3 by Alexander Belchenko
commands.py: main() function expect to get argv argument as list of unicode or pure ascii strings.
1258
            # ensure all arguments are unicode strings
5785.1.2 by Martin
Move _specified_or_unicode_argv call inside run_bzr as it may raise an error that should be reported
1259
            for a in argv:
4355.2.3 by Alexander Belchenko
commands.py: main() function expect to get argv argument as list of unicode or pure ascii strings.
1260
                if isinstance(a, unicode):
1261
                    new_argv.append(a)
1262
                else:
1263
                    new_argv.append(a.decode('ascii'))
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
1264
        except UnicodeDecodeError:
1265
            raise errors.BzrError("argv should be list of unicode strings.")
5017.1.1 by Martin Pool
Add bzrlib.initialize
1266
        return new_argv
1267
1268
1269
def main(argv=None):
1270
    """Main entry point of command-line interface.
1271
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
1272
    Typically `breezy.initialize` should be called first.
5017.1.1 by Martin Pool
Add bzrlib.initialize
1273
1274
    :param argv: list of unicode command-line arguments similar to sys.argv.
1275
        argv[0] is script name usually, it will be ignored.
1276
        Don't pass here sys.argv because this list contains plain strings
1277
        and not unicode; pass None instead.
1278
6622.1.1 by Jelmer Vernooij
Rename bzrlib => brzlib, bzr => brz.
1279
    :return: exit code of brz command.
5017.1.1 by Martin Pool
Add bzrlib.initialize
1280
    """
5785.1.2 by Martin
Move _specified_or_unicode_argv call inside run_bzr as it may raise an error that should be reported
1281
    if argv is not None:
1282
        argv = argv[1:]
5018.1.3 by Martin Pool
Put builtin commands into a real registry
1283
    _register_builtin_commands()
1185.85.4 by John Arbash Meinel
currently broken, trying to fix things up.
1284
    ret = run_bzr_catch_errors(argv)
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
1285
    trace.mutter("return code %d", ret)
1185.43.6 by Martin Pool
Enable logging early enough to save argv
1286
    return ret
1185.3.19 by Martin Pool
- split out commandline error reporting for ease of testing
1287
1288
1289
def run_bzr_catch_errors(argv):
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1290
    """Run a bzr command with parameters as described by argv.
4084.6.3 by Robert Collins
Disagreement on trailing whitespace with the test suite.
1291
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1292
    This function assumed that that UI layer is setup, that symbol deprecations
1293
    are already applied, and that unicode decoding has already been performed on argv.
1294
    """
5017.1.1 by Martin Pool
Add bzrlib.initialize
1295
    # done here so that they're covered for every test run
4119.3.13 by Robert Collins
Unbreak blackbox tests.
1296
    install_bzr_command_hooks()
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
1297
    return exception_to_return_code(run_bzr, argv)
1 by mbp at sourcefrog
import from baz patch-364
1298
2432.1.2 by Robert Collins
Add a HelpCommandContext class for help from commands.
1299
2830.2.1 by Martin Pool
If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
1300
def run_bzr_catch_user_errors(argv):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1301
    """Run brz and report user errors, but let internal errors propagate.
2830.2.1 by Martin Pool
If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
1302
1303
    This is used for the test suite, and might be useful for other programs
1304
    that want to wrap the commandline interface.
1305
    """
5017.1.1 by Martin Pool
Add bzrlib.initialize
1306
    # done here so that they're covered for every test run
4119.3.13 by Robert Collins
Unbreak blackbox tests.
1307
    install_bzr_command_hooks()
2830.2.1 by Martin Pool
If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
1308
    try:
1309
        return run_bzr(argv)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1310
    except Exception as e:
2830.2.1 by Martin Pool
If TestCase.run_bzr hits an internal exception, don't catch it but rather propagate up into the test suite
1311
        if (isinstance(e, (OSError, IOError))
1312
            or not getattr(e, 'internal_error', True)):
1313
            trace.report_exception(sys.exc_info(), sys.stderr)
1314
            return 3
1315
        else:
1316
            raise
1317
1318
2432.1.15 by Robert Collins
Rename Context (in bzrlib.help) to Index, for a clearer name.
1319
class HelpCommandIndex(object):
1320
    """A index for bzr help that returns commands."""
2432.1.2 by Robert Collins
Add a HelpCommandContext class for help from commands.
1321
2432.1.17 by Robert Collins
Add prefixes to HelpIndexes.
1322
    def __init__(self):
1323
        self.prefix = 'commands/'
1324
2432.1.13 by Robert Collins
HelpCommandContext now implementes get_topics.
1325
    def get_topics(self, topic):
1326
        """Search for topic amongst commands.
1327
1328
        :param topic: A topic to search for.
1329
        :return: A list which is either empty or contains a single
1330
            Command entry.
1331
        """
2432.1.18 by Robert Collins
Add support for doing bzr help commands/COMMANDNAME.
1332
        if topic and topic.startswith(self.prefix):
1333
            topic = topic[len(self.prefix):]
2432.1.13 by Robert Collins
HelpCommandContext now implementes get_topics.
1334
        try:
5058.2.1 by Robert Collins
* ``bzr help`` will no longer trigger the get_missing_command hook when
1335
            cmd = _get_cmd_object(topic, check_missing=False)
2432.1.13 by Robert Collins
HelpCommandContext now implementes get_topics.
1336
        except KeyError:
1337
            return []
1338
        else:
1339
            return [cmd]
1340
2432.1.2 by Robert Collins
Add a HelpCommandContext class for help from commands.
1341
3246.7.1 by Martin Albisetti
Core code for automatic plugin suggestion
1342
class Provider(object):
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1343
    """Generic class to be overriden by plugins"""
3246.7.1 by Martin Albisetti
Core code for automatic plugin suggestion
1344
1345
    def plugin_for_command(self, cmd_name):
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1346
        """Takes a command and returns the information for that plugin
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1347
1348
        :return: A dictionary with all the available information
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1349
            for the requested plugin
1350
        """
3246.7.1 by Martin Albisetti
Core code for automatic plugin suggestion
1351
        raise NotImplementedError
1352
1353
1354
class ProvidersRegistry(registry.Registry):
5891.1.3 by Andrew Bennetts
Move docstring formatting fixes.
1355
    """This registry exists to allow other providers to exist"""
3246.7.3 by Martin Albisetti
Code cleanup and documentation
1356
3246.7.1 by Martin Albisetti
Core code for automatic plugin suggestion
1357
    def __iter__(self):
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
1358
        for key, provider in self.items():
3246.7.1 by Martin Albisetti
Core code for automatic plugin suggestion
1359
            yield provider
1360
1361
command_providers_registry = ProvidersRegistry()