~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Ian Clatworthy
  • Date: 2009-09-02 16:03:51 UTC
  • mto: (4634.39.1 pdf-chm-docs)
  • mto: This revision was merged to the branch mainline in revision 4689.
  • Revision ID: ian.clatworthy@canonical.com-20090902160351-sxptcz3ttc1aencw
first cut at pdf docs via sphinx

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2008 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
# TODO: probably should say which arguments are candidates for glob
 
19
# expansion on windows and do that at the command level.
 
20
 
 
21
# TODO: Define arguments by objects, rather than just using names.
 
22
# Those objects can specify the expected type of the argument, which
 
23
# would help with validation and shell completion.  They could also provide
 
24
# help/explanation for that argument in a structured way.
 
25
 
 
26
# TODO: Specific "examples" property on commands for consistent formatting.
 
27
 
 
28
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
 
29
# the profile output behind so it can be interactively examined?
 
30
 
 
31
import os
 
32
import sys
 
33
 
 
34
from bzrlib.lazy_import import lazy_import
 
35
lazy_import(globals(), """
 
36
import codecs
 
37
import errno
 
38
import threading
 
39
from warnings import warn
 
40
 
 
41
import bzrlib
 
42
from bzrlib import (
 
43
    debug,
 
44
    errors,
 
45
    option,
 
46
    osutils,
 
47
    trace,
 
48
    win32utils,
 
49
    )
 
50
""")
 
51
 
 
52
from bzrlib.hooks import HookPoint, Hooks
 
53
# Compatibility - Option used to be in commands.
 
54
from bzrlib.option import Option
 
55
from bzrlib import registry
 
56
from bzrlib.symbol_versioning import (
 
57
    deprecated_function,
 
58
    deprecated_in,
 
59
    suppress_deprecation_warnings,
 
60
    )
 
61
 
 
62
 
 
63
class CommandInfo(object):
 
64
    """Information about a command."""
 
65
 
 
66
    def __init__(self, aliases):
 
67
        """The list of aliases for the command."""
 
68
        self.aliases = aliases
 
69
 
 
70
    @classmethod
 
71
    def from_command(klass, command):
 
72
        """Factory to construct a CommandInfo from a command."""
 
73
        return klass(command.aliases)
 
74
 
 
75
 
 
76
class CommandRegistry(registry.Registry):
 
77
 
 
78
    @staticmethod
 
79
    def _get_name(command_name):
 
80
        if command_name.startswith("cmd_"):
 
81
            return _unsquish_command_name(command_name)
 
82
        else:
 
83
            return command_name
 
84
 
 
85
    def register(self, cmd, decorate=False):
 
86
        """Utility function to help register a command
 
87
 
 
88
        :param cmd: Command subclass to register
 
89
        :param decorate: If true, allow overriding an existing command
 
90
            of the same name; the old command is returned by this function.
 
91
            Otherwise it is an error to try to override an existing command.
 
92
        """
 
93
        k = cmd.__name__
 
94
        k_unsquished = self._get_name(k)
 
95
        try:
 
96
            previous = self.get(k_unsquished)
 
97
        except KeyError:
 
98
            previous = _builtin_commands().get(k_unsquished)
 
99
        info = CommandInfo.from_command(cmd)
 
100
        try:
 
101
            registry.Registry.register(self, k_unsquished, cmd,
 
102
                                       override_existing=decorate, info=info)
 
103
        except KeyError:
 
104
            trace.log_error('Two plugins defined the same command: %r' % k)
 
105
            trace.log_error('Not loading the one in %r' %
 
106
                            sys.modules[cmd.__module__])
 
107
            trace.log_error('Previously this command was registered from %r' %
 
108
                            sys.modules[previous.__module__])
 
109
        return previous
 
110
 
 
111
    def register_lazy(self, command_name, aliases, module_name):
 
112
        """Register a command without loading its module.
 
113
 
 
114
        :param command_name: The primary name of the command.
 
115
        :param aliases: A list of aliases for the command.
 
116
        :module_name: The module that the command lives in.
 
117
        """
 
118
        key = self._get_name(command_name)
 
119
        registry.Registry.register_lazy(self, key, module_name, command_name,
 
120
                                        info=CommandInfo(aliases))
 
121
 
 
122
 
 
123
plugin_cmds = CommandRegistry()
 
124
 
 
125
 
 
126
def register_command(cmd, decorate=False):
 
127
    global plugin_cmds
 
128
    return plugin_cmds.register(cmd, decorate)
 
129
 
 
130
 
 
131
def _squish_command_name(cmd):
 
132
    return 'cmd_' + cmd.replace('-', '_')
 
133
 
 
134
 
 
135
def _unsquish_command_name(cmd):
 
136
    return cmd[4:].replace('_','-')
 
137
 
 
138
 
 
139
def _builtin_commands():
 
140
    import bzrlib.builtins
 
141
    return _scan_module_for_commands(bzrlib.builtins)
 
142
 
 
143
 
 
144
def _scan_module_for_commands(module):
 
145
    r = {}
 
146
    for name, obj in module.__dict__.iteritems():
 
147
        if name.startswith("cmd_"):
 
148
            real_name = _unsquish_command_name(name)
 
149
            r[real_name] = obj
 
150
    return r
 
151
 
 
152
 
 
153
def _list_bzr_commands(names):
 
154
    """Find commands from bzr's core and plugins."""
 
155
    # to eliminate duplicates
 
156
    names.update(builtin_command_names())
 
157
    names.update(plugin_command_names())
 
158
    return names
 
159
 
 
160
 
 
161
def all_command_names():
 
162
    """Return a set of all command names."""
 
163
    names = set()
 
164
    for hook in Command.hooks['list_commands']:
 
165
        names = hook(names)
 
166
        if names is None:
 
167
            raise AssertionError(
 
168
                'hook %s returned None' % Command.hooks.get_hook_name(hook))
 
169
    return names
 
170
 
 
171
 
 
172
def builtin_command_names():
 
173
    """Return list of builtin command names.
 
174
    
 
175
    Use of all_command_names() is encouraged rather than builtin_command_names
 
176
    and/or plugin_command_names.
 
177
    """
 
178
    return _builtin_commands().keys()
 
179
 
 
180
 
 
181
def plugin_command_names():
 
182
    """Returns command names from commands registered by plugins."""
 
183
    return plugin_cmds.keys()
 
184
 
 
185
 
 
186
@deprecated_function(deprecated_in((1, 17, 0)))
 
187
def get_all_cmds(plugins_override=False):
 
188
    """Return canonical name and class for most commands.
 
189
    
 
190
    NB: This does not return all commands since the introduction of
 
191
    command hooks, and returning the class is not sufficient to 
 
192
    get correctly setup commands, which is why it is deprecated.
 
193
 
 
194
    Use 'all_command_names' + 'get_cmd_object' instead.
 
195
    """
 
196
    d = _builtin_commands()
 
197
    if plugins_override:
 
198
        d.update(plugin_cmds.iteritems())
 
199
    for k, v in d.iteritems():
 
200
        yield k,v
 
201
 
 
202
 
 
203
def get_cmd_object(cmd_name, plugins_override=True):
 
204
    """Return the command object for a command.
 
205
 
 
206
    plugins_override
 
207
        If true, plugin commands can override builtins.
 
208
    """
 
209
    try:
 
210
        return _get_cmd_object(cmd_name, plugins_override)
 
211
    except KeyError:
 
212
        raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
 
213
 
 
214
 
 
215
def _get_cmd_object(cmd_name, plugins_override=True):
 
216
    """Get a command object.
 
217
 
 
218
    :param cmd_name: The name of the command.
 
219
    :param plugins_override: Allow plugins to override builtins.
 
220
    :return: A Command object instance
 
221
    :raises KeyError: If no command is found.
 
222
    """
 
223
    # We want only 'ascii' command names, but the user may have typed
 
224
    # in a Unicode name. In that case, they should just get a
 
225
    # 'command not found' error later.
 
226
    # In the future, we may actually support Unicode command names.
 
227
    cmd = None
 
228
    # Get a command
 
229
    for hook in Command.hooks['get_command']:
 
230
        cmd = hook(cmd, cmd_name)
 
231
        if cmd is not None and not plugins_override and not cmd.plugin_name():
 
232
            # We've found a non-plugin command, don't permit it to be
 
233
            # overridden.
 
234
            break
 
235
    if cmd is None:
 
236
        for hook in Command.hooks['get_missing_command']:
 
237
            cmd = hook(cmd_name)
 
238
            if cmd is not None:
 
239
                break
 
240
    if cmd is None:
 
241
        # No command found.
 
242
        raise KeyError
 
243
    # Allow plugins to extend commands
 
244
    for hook in Command.hooks['extend_command']:
 
245
        hook(cmd)
 
246
    return cmd
 
247
 
 
248
 
 
249
def _try_plugin_provider(cmd_name):
 
250
    """Probe for a plugin provider having cmd_name."""
 
251
    try:
 
252
        plugin_metadata, provider = probe_for_provider(cmd_name)
 
253
        raise errors.CommandAvailableInPlugin(cmd_name,
 
254
            plugin_metadata, provider)
 
255
    except errors.NoPluginAvailable:
 
256
        pass
 
257
 
 
258
 
 
259
def probe_for_provider(cmd_name):
 
260
    """Look for a provider for cmd_name.
 
261
 
 
262
    :param cmd_name: The command name.
 
263
    :return: plugin_metadata, provider for getting cmd_name.
 
264
    :raises NoPluginAvailable: When no provider can supply the plugin.
 
265
    """
 
266
    # look for providers that provide this command but aren't installed
 
267
    for provider in command_providers_registry:
 
268
        try:
 
269
            return provider.plugin_for_command(cmd_name), provider
 
270
        except errors.NoPluginAvailable:
 
271
            pass
 
272
    raise errors.NoPluginAvailable(cmd_name)
 
273
 
 
274
 
 
275
def _get_bzr_command(cmd_or_None, cmd_name):
 
276
    """Get a command from bzr's core."""
 
277
    cmds = _builtin_commands()
 
278
    try:
 
279
        return cmds[cmd_name]()
 
280
    except KeyError:
 
281
        pass
 
282
    # look for any command which claims this as an alias
 
283
    for real_cmd_name, cmd_class in cmds.iteritems():
 
284
        if cmd_name in cmd_class.aliases:
 
285
            return cmd_class()
 
286
    return cmd_or_None
 
287
 
 
288
 
 
289
def _get_external_command(cmd_or_None, cmd_name):
 
290
    """Lookup a command that is a shell script."""
 
291
    # Only do external command lookups when no command is found so far.
 
292
    if cmd_or_None is not None:
 
293
        return cmd_or_None
 
294
    from bzrlib.externalcommand import ExternalCommand
 
295
    cmd_obj = ExternalCommand.find_command(cmd_name)
 
296
    if cmd_obj:
 
297
        return cmd_obj
 
298
 
 
299
 
 
300
def _get_plugin_command(cmd_or_None, cmd_name):
 
301
    """Get a command from bzr's plugins."""
 
302
    try:
 
303
        return plugin_cmds.get(cmd_name)()
 
304
    except KeyError:
 
305
        pass
 
306
    for key in plugin_cmds.keys():
 
307
        info = plugin_cmds.get_info(key)
 
308
        if cmd_name in info.aliases:
 
309
            return plugin_cmds.get(key)()
 
310
    return cmd_or_None
 
311
 
 
312
 
 
313
class Command(object):
 
314
    """Base class for commands.
 
315
 
 
316
    Commands are the heart of the command-line bzr interface.
 
317
 
 
318
    The command object mostly handles the mapping of command-line
 
319
    parameters into one or more bzrlib operations, and of the results
 
320
    into textual output.
 
321
 
 
322
    Commands normally don't have any state.  All their arguments are
 
323
    passed in to the run method.  (Subclasses may take a different
 
324
    policy if the behaviour of the instance needs to depend on e.g. a
 
325
    shell plugin and not just its Python class.)
 
326
 
 
327
    The docstring for an actual command should give a single-line
 
328
    summary, then a complete description of the command.  A grammar
 
329
    description will be inserted.
 
330
 
 
331
    aliases
 
332
        Other accepted names for this command.
 
333
 
 
334
    takes_args
 
335
        List of argument forms, marked with whether they are optional,
 
336
        repeated, etc.
 
337
 
 
338
                Examples:
 
339
 
 
340
                ['to_location', 'from_branch?', 'file*']
 
341
 
 
342
                'to_location' is required
 
343
                'from_branch' is optional
 
344
                'file' can be specified 0 or more times
 
345
 
 
346
    takes_options
 
347
        List of options that may be given for this command.  These can
 
348
        be either strings, referring to globally-defined options,
 
349
        or option objects.  Retrieve through options().
 
350
 
 
351
    hidden
 
352
        If true, this command isn't advertised.  This is typically
 
353
        for commands intended for expert users.
 
354
 
 
355
    encoding_type
 
356
        Command objects will get a 'outf' attribute, which has been
 
357
        setup to properly handle encoding of unicode strings.
 
358
        encoding_type determines what will happen when characters cannot
 
359
        be encoded
 
360
            strict - abort if we cannot decode
 
361
            replace - put in a bogus character (typically '?')
 
362
            exact - do not encode sys.stdout
 
363
 
 
364
            NOTE: by default on Windows, sys.stdout is opened as a text
 
365
            stream, therefore LF line-endings are converted to CRLF.
 
366
            When a command uses encoding_type = 'exact', then
 
367
            sys.stdout is forced to be a binary stream, and line-endings
 
368
            will not mangled.
 
369
 
 
370
    :cvar hooks: An instance of CommandHooks.
 
371
    """
 
372
    aliases = []
 
373
    takes_args = []
 
374
    takes_options = []
 
375
    encoding_type = 'strict'
 
376
 
 
377
    hidden = False
 
378
 
 
379
    def __init__(self):
 
380
        """Construct an instance of this command."""
 
381
        if self.__doc__ == Command.__doc__:
 
382
            warn("No help message set for %r" % self)
 
383
        # List of standard options directly supported
 
384
        self.supported_std_options = []
 
385
 
 
386
    def _maybe_expand_globs(self, file_list):
 
387
        """Glob expand file_list if the platform does not do that itself.
 
388
 
 
389
        :return: A possibly empty list of unicode paths.
 
390
 
 
391
        Introduced in bzrlib 0.18.
 
392
        """
 
393
        if not file_list:
 
394
            file_list = []
 
395
        if sys.platform == 'win32':
 
396
            file_list = win32utils.glob_expand(file_list)
 
397
        return list(file_list)
 
398
 
 
399
    def _usage(self):
 
400
        """Return single-line grammar for this command.
 
401
 
 
402
        Only describes arguments, not options.
 
403
        """
 
404
        s = 'bzr ' + self.name() + ' '
 
405
        for aname in self.takes_args:
 
406
            aname = aname.upper()
 
407
            if aname[-1] in ['$', '+']:
 
408
                aname = aname[:-1] + '...'
 
409
            elif aname[-1] == '?':
 
410
                aname = '[' + aname[:-1] + ']'
 
411
            elif aname[-1] == '*':
 
412
                aname = '[' + aname[:-1] + '...]'
 
413
            s += aname + ' '
 
414
        s = s[:-1]      # remove last space
 
415
        return s
 
416
 
 
417
    def get_help_text(self, additional_see_also=None, plain=True,
 
418
                      see_also_as_links=False, verbose=True):
 
419
        """Return a text string with help for this command.
 
420
 
 
421
        :param additional_see_also: Additional help topics to be
 
422
            cross-referenced.
 
423
        :param plain: if False, raw help (reStructuredText) is
 
424
            returned instead of plain text.
 
425
        :param see_also_as_links: if True, convert items in 'See also'
 
426
            list to internal links (used by bzr_man rstx generator)
 
427
        :param verbose: if True, display the full help, otherwise
 
428
            leave out the descriptive sections and just display
 
429
            usage help (e.g. Purpose, Usage, Options) with a
 
430
            message explaining how to obtain full help.
 
431
        """
 
432
        doc = self.help()
 
433
        if doc is None:
 
434
            raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
 
435
 
 
436
        # Extract the summary (purpose) and sections out from the text
 
437
        purpose,sections,order = self._get_help_parts(doc)
 
438
 
 
439
        # If a custom usage section was provided, use it
 
440
        if sections.has_key('Usage'):
 
441
            usage = sections.pop('Usage')
 
442
        else:
 
443
            usage = self._usage()
 
444
 
 
445
        # The header is the purpose and usage
 
446
        result = ""
 
447
        result += ':Purpose: %s\n' % purpose
 
448
        if usage.find('\n') >= 0:
 
449
            result += ':Usage:\n%s\n' % usage
 
450
        else:
 
451
            result += ':Usage:   %s\n' % usage
 
452
        result += '\n'
 
453
 
 
454
        # Add the options
 
455
        #
 
456
        # XXX: optparse implicitly rewraps the help, and not always perfectly,
 
457
        # so we get <https://bugs.launchpad.net/bzr/+bug/249908>.  -- mbp
 
458
        # 20090319
 
459
        options = option.get_optparser(self.options()).format_option_help()
 
460
        if options.startswith('Options:'):
 
461
            result += ':' + options
 
462
        elif options.startswith('options:'):
 
463
            # Python 2.4 version of optparse
 
464
            result += ':Options:' + options[len('options:'):]
 
465
        else:
 
466
            result += options
 
467
        result += '\n'
 
468
 
 
469
        if verbose:
 
470
            # Add the description, indenting it 2 spaces
 
471
            # to match the indentation of the options
 
472
            if sections.has_key(None):
 
473
                text = sections.pop(None)
 
474
                text = '\n  '.join(text.splitlines())
 
475
                result += ':%s:\n  %s\n\n' % ('Description',text)
 
476
 
 
477
            # Add the custom sections (e.g. Examples). Note that there's no need
 
478
            # to indent these as they must be indented already in the source.
 
479
            if sections:
 
480
                for label in order:
 
481
                    if sections.has_key(label):
 
482
                        result += ':%s:\n%s\n' % (label,sections[label])
 
483
                result += '\n'
 
484
        else:
 
485
            result += ("See bzr help %s for more details and examples.\n\n"
 
486
                % self.name())
 
487
 
 
488
        # Add the aliases, source (plug-in) and see also links, if any
 
489
        if self.aliases:
 
490
            result += ':Aliases:  '
 
491
            result += ', '.join(self.aliases) + '\n'
 
492
        plugin_name = self.plugin_name()
 
493
        if plugin_name is not None:
 
494
            result += ':From:     plugin "%s"\n' % plugin_name
 
495
        see_also = self.get_see_also(additional_see_also)
 
496
        if see_also:
 
497
            if not plain and see_also_as_links:
 
498
                see_also_links = []
 
499
                for item in see_also:
 
500
                    if item == 'topics':
 
501
                        # topics doesn't have an independent section
 
502
                        # so don't create a real link
 
503
                        see_also_links.append(item)
 
504
                    else:
 
505
                        # Use a reST link for this entry
 
506
                        see_also_links.append("`%s`_" % (item,))
 
507
                see_also = see_also_links
 
508
            result += ':See also: '
 
509
            result += ', '.join(see_also) + '\n'
 
510
 
 
511
        # If this will be rendered as plain text, convert it
 
512
        if plain:
 
513
            import bzrlib.help_topics
 
514
            result = bzrlib.help_topics.help_as_plain_text(result)
 
515
        return result
 
516
 
 
517
    @staticmethod
 
518
    def _get_help_parts(text):
 
519
        """Split help text into a summary and named sections.
 
520
 
 
521
        :return: (summary,sections,order) where summary is the top line and
 
522
            sections is a dictionary of the rest indexed by section name.
 
523
            order is the order the section appear in the text.
 
524
            A section starts with a heading line of the form ":xxx:".
 
525
            Indented text on following lines is the section value.
 
526
            All text found outside a named section is assigned to the
 
527
            default section which is given the key of None.
 
528
        """
 
529
        def save_section(sections, order, label, section):
 
530
            if len(section) > 0:
 
531
                if sections.has_key(label):
 
532
                    sections[label] += '\n' + section
 
533
                else:
 
534
                    order.append(label)
 
535
                    sections[label] = section
 
536
 
 
537
        lines = text.rstrip().splitlines()
 
538
        summary = lines.pop(0)
 
539
        sections = {}
 
540
        order = []
 
541
        label,section = None,''
 
542
        for line in lines:
 
543
            if line.startswith(':') and line.endswith(':') and len(line) > 2:
 
544
                save_section(sections, order, label, section)
 
545
                label,section = line[1:-1],''
 
546
            elif (label is not None) and len(line) > 1 and not line[0].isspace():
 
547
                save_section(sections, order, label, section)
 
548
                label,section = None,line
 
549
            else:
 
550
                if len(section) > 0:
 
551
                    section += '\n' + line
 
552
                else:
 
553
                    section = line
 
554
        save_section(sections, order, label, section)
 
555
        return summary, sections, order
 
556
 
 
557
    def get_help_topic(self):
 
558
        """Return the commands help topic - its name."""
 
559
        return self.name()
 
560
 
 
561
    def get_see_also(self, additional_terms=None):
 
562
        """Return a list of help topics that are related to this command.
 
563
 
 
564
        The list is derived from the content of the _see_also attribute. Any
 
565
        duplicates are removed and the result is in lexical order.
 
566
        :param additional_terms: Additional help topics to cross-reference.
 
567
        :return: A list of help topics.
 
568
        """
 
569
        see_also = set(getattr(self, '_see_also', []))
 
570
        if additional_terms:
 
571
            see_also.update(additional_terms)
 
572
        return sorted(see_also)
 
573
 
 
574
    def options(self):
 
575
        """Return dict of valid options for this command.
 
576
 
 
577
        Maps from long option name to option object."""
 
578
        r = Option.STD_OPTIONS.copy()
 
579
        std_names = r.keys()
 
580
        for o in self.takes_options:
 
581
            if isinstance(o, basestring):
 
582
                o = option.Option.OPTIONS[o]
 
583
            r[o.name] = o
 
584
            if o.name in std_names:
 
585
                self.supported_std_options.append(o.name)
 
586
        return r
 
587
 
 
588
    def _setup_outf(self):
 
589
        """Return a file linked to stdout, which has proper encoding."""
 
590
        # Originally I was using self.stdout, but that looks
 
591
        # *way* too much like sys.stdout
 
592
        if self.encoding_type == 'exact':
 
593
            # force sys.stdout to be binary stream on win32
 
594
            if sys.platform == 'win32':
 
595
                fileno = getattr(sys.stdout, 'fileno', None)
 
596
                if fileno:
 
597
                    import msvcrt
 
598
                    msvcrt.setmode(fileno(), os.O_BINARY)
 
599
            self.outf = sys.stdout
 
600
            return
 
601
 
 
602
        output_encoding = osutils.get_terminal_encoding()
 
603
 
 
604
        self.outf = codecs.getwriter(output_encoding)(sys.stdout,
 
605
                        errors=self.encoding_type)
 
606
        # For whatever reason codecs.getwriter() does not advertise its encoding
 
607
        # it just returns the encoding of the wrapped file, which is completely
 
608
        # bogus. So set the attribute, so we can find the correct encoding later.
 
609
        self.outf.encoding = output_encoding
 
610
 
 
611
    def run_argv_aliases(self, argv, alias_argv=None):
 
612
        """Parse the command line and run with extra aliases in alias_argv."""
 
613
        if argv is None:
 
614
            warn("Passing None for [] is deprecated from bzrlib 0.10",
 
615
                 DeprecationWarning, stacklevel=2)
 
616
            argv = []
 
617
        args, opts = parse_args(self, argv, alias_argv)
 
618
 
 
619
        # Process the standard options
 
620
        if 'help' in opts:  # e.g. bzr add --help
 
621
            sys.stdout.write(self.get_help_text())
 
622
            return 0
 
623
        if 'usage' in opts:  # e.g. bzr add --usage
 
624
            sys.stdout.write(self.get_help_text(verbose=False))
 
625
            return 0
 
626
        trace.set_verbosity_level(option._verbosity_level)
 
627
        if 'verbose' in self.supported_std_options:
 
628
            opts['verbose'] = trace.is_verbose()
 
629
        elif opts.has_key('verbose'):
 
630
            del opts['verbose']
 
631
        if 'quiet' in self.supported_std_options:
 
632
            opts['quiet'] = trace.is_quiet()
 
633
        elif opts.has_key('quiet'):
 
634
            del opts['quiet']
 
635
 
 
636
        # mix arguments and options into one dictionary
 
637
        cmdargs = _match_argform(self.name(), self.takes_args, args)
 
638
        cmdopts = {}
 
639
        for k, v in opts.items():
 
640
            cmdopts[k.replace('-', '_')] = v
 
641
 
 
642
        all_cmd_args = cmdargs.copy()
 
643
        all_cmd_args.update(cmdopts)
 
644
 
 
645
        self._setup_outf()
 
646
 
 
647
        return self.run(**all_cmd_args)
 
648
 
 
649
    def run(self):
 
650
        """Actually run the command.
 
651
 
 
652
        This is invoked with the options and arguments bound to
 
653
        keyword parameters.
 
654
 
 
655
        Return 0 or None if the command was successful, or a non-zero
 
656
        shell error code if not.  It's OK for this method to allow
 
657
        an exception to raise up.
 
658
        """
 
659
        raise NotImplementedError('no implementation of command %r'
 
660
                                  % self.name())
 
661
 
 
662
    def help(self):
 
663
        """Return help message for this class."""
 
664
        from inspect import getdoc
 
665
        if self.__doc__ is Command.__doc__:
 
666
            return None
 
667
        return getdoc(self)
 
668
 
 
669
    def name(self):
 
670
        return _unsquish_command_name(self.__class__.__name__)
 
671
 
 
672
    def plugin_name(self):
 
673
        """Get the name of the plugin that provides this command.
 
674
 
 
675
        :return: The name of the plugin or None if the command is builtin.
 
676
        """
 
677
        mod_parts = self.__module__.split('.')
 
678
        if len(mod_parts) >= 3 and mod_parts[1] == 'plugins':
 
679
            return mod_parts[2]
 
680
        else:
 
681
            return None
 
682
 
 
683
 
 
684
class CommandHooks(Hooks):
 
685
    """Hooks related to Command object creation/enumeration."""
 
686
 
 
687
    def __init__(self):
 
688
        """Create the default hooks.
 
689
 
 
690
        These are all empty initially, because by default nothing should get
 
691
        notified.
 
692
        """
 
693
        Hooks.__init__(self)
 
694
        self.create_hook(HookPoint('extend_command',
 
695
            "Called after creating a command object to allow modifications "
 
696
            "such as adding or removing options, docs etc. Called with the "
 
697
            "new bzrlib.commands.Command object.", (1, 13), None))
 
698
        self.create_hook(HookPoint('get_command',
 
699
            "Called when creating a single command. Called with "
 
700
            "(cmd_or_None, command_name). get_command should either return "
 
701
            "the cmd_or_None parameter, or a replacement Command object that "
 
702
            "should be used for the command. Note that the Command.hooks "
 
703
            "hooks are core infrastructure. Many users will prefer to use "
 
704
            "bzrlib.commands.register_command or plugin_cmds.register_lazy.",
 
705
            (1, 17), None))
 
706
        self.create_hook(HookPoint('get_missing_command',
 
707
            "Called when creating a single command if no command could be "
 
708
            "found. Called with (command_name). get_missing_command should "
 
709
            "either return None, or a Command object to be used for the "
 
710
            "command.", (1, 17), None))
 
711
        self.create_hook(HookPoint('list_commands',
 
712
            "Called when enumerating commands. Called with a set of "
 
713
            "cmd_name strings for all the commands found so far. This set "
 
714
            " is safe to mutate - e.g. to remove a command. "
 
715
            "list_commands should return the updated set of command names.",
 
716
            (1, 17), None))
 
717
 
 
718
Command.hooks = CommandHooks()
 
719
 
 
720
 
 
721
def parse_args(command, argv, alias_argv=None):
 
722
    """Parse command line.
 
723
 
 
724
    Arguments and options are parsed at this level before being passed
 
725
    down to specific command handlers.  This routine knows, from a
 
726
    lookup table, something about the available options, what optargs
 
727
    they take, and which commands will accept them.
 
728
    """
 
729
    # TODO: make it a method of the Command?
 
730
    parser = option.get_optparser(command.options())
 
731
    if alias_argv is not None:
 
732
        args = alias_argv + argv
 
733
    else:
 
734
        args = argv
 
735
 
 
736
    options, args = parser.parse_args(args)
 
737
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
 
738
                 v is not option.OptionParser.DEFAULT_VALUE])
 
739
    return args, opts
 
740
 
 
741
 
 
742
def _match_argform(cmd, takes_args, args):
 
743
    argdict = {}
 
744
 
 
745
    # step through args and takes_args, allowing appropriate 0-many matches
 
746
    for ap in takes_args:
 
747
        argname = ap[:-1]
 
748
        if ap[-1] == '?':
 
749
            if args:
 
750
                argdict[argname] = args.pop(0)
 
751
        elif ap[-1] == '*': # all remaining arguments
 
752
            if args:
 
753
                argdict[argname + '_list'] = args[:]
 
754
                args = []
 
755
            else:
 
756
                argdict[argname + '_list'] = None
 
757
        elif ap[-1] == '+':
 
758
            if not args:
 
759
                raise errors.BzrCommandError("command %r needs one or more %s"
 
760
                                             % (cmd, argname.upper()))
 
761
            else:
 
762
                argdict[argname + '_list'] = args[:]
 
763
                args = []
 
764
        elif ap[-1] == '$': # all but one
 
765
            if len(args) < 2:
 
766
                raise errors.BzrCommandError("command %r needs one or more %s"
 
767
                                             % (cmd, argname.upper()))
 
768
            argdict[argname + '_list'] = args[:-1]
 
769
            args[:-1] = []
 
770
        else:
 
771
            # just a plain arg
 
772
            argname = ap
 
773
            if not args:
 
774
                raise errors.BzrCommandError("command %r requires argument %s"
 
775
                               % (cmd, argname.upper()))
 
776
            else:
 
777
                argdict[argname] = args.pop(0)
 
778
 
 
779
    if args:
 
780
        raise errors.BzrCommandError("extra argument to command %s: %s"
 
781
                                     % (cmd, args[0]))
 
782
 
 
783
    return argdict
 
784
 
 
785
def apply_coveraged(dirname, the_callable, *args, **kwargs):
 
786
    # Cannot use "import trace", as that would import bzrlib.trace instead of
 
787
    # the standard library's trace.
 
788
    trace = __import__('trace')
 
789
 
 
790
    tracer = trace.Trace(count=1, trace=0)
 
791
    sys.settrace(tracer.globaltrace)
 
792
    threading.settrace(tracer.globaltrace)
 
793
 
 
794
    try:
 
795
        return exception_to_return_code(the_callable, *args, **kwargs)
 
796
    finally:
 
797
        sys.settrace(None)
 
798
        results = tracer.results()
 
799
        results.write_results(show_missing=1, summary=False,
 
800
                              coverdir=dirname)
 
801
 
 
802
 
 
803
def apply_profiled(the_callable, *args, **kwargs):
 
804
    import hotshot
 
805
    import tempfile
 
806
    import hotshot.stats
 
807
    pffileno, pfname = tempfile.mkstemp()
 
808
    try:
 
809
        prof = hotshot.Profile(pfname)
 
810
        try:
 
811
            ret = prof.runcall(exception_to_return_code, the_callable, *args,
 
812
                **kwargs) or 0
 
813
        finally:
 
814
            prof.close()
 
815
        stats = hotshot.stats.load(pfname)
 
816
        stats.strip_dirs()
 
817
        stats.sort_stats('cum')   # 'time'
 
818
        ## XXX: Might like to write to stderr or the trace file instead but
 
819
        ## print_stats seems hardcoded to stdout
 
820
        stats.print_stats(20)
 
821
        return ret
 
822
    finally:
 
823
        os.close(pffileno)
 
824
        os.remove(pfname)
 
825
 
 
826
 
 
827
def exception_to_return_code(the_callable, *args, **kwargs):
 
828
    """UI level helper for profiling and coverage.
 
829
 
 
830
    This transforms exceptions into a return value of 3. As such its only
 
831
    relevant to the UI layer, and should never be called where catching
 
832
    exceptions may be desirable.
 
833
    """
 
834
    try:
 
835
        return the_callable(*args, **kwargs)
 
836
    except (KeyboardInterrupt, Exception), e:
 
837
        # used to handle AssertionError and KeyboardInterrupt
 
838
        # specially here, but hopefully they're handled ok by the logger now
 
839
        exc_info = sys.exc_info()
 
840
        exitcode = trace.report_exception(exc_info, sys.stderr)
 
841
        if os.environ.get('BZR_PDB'):
 
842
            print '**** entering debugger'
 
843
            tb = exc_info[2]
 
844
            import pdb
 
845
            if sys.version_info[:2] < (2, 6):
 
846
                # XXX: we want to do
 
847
                #    pdb.post_mortem(tb)
 
848
                # but because pdb.post_mortem gives bad results for tracebacks
 
849
                # from inside generators, we do it manually.
 
850
                # (http://bugs.python.org/issue4150, fixed in Python 2.6)
 
851
 
 
852
                # Setup pdb on the traceback
 
853
                p = pdb.Pdb()
 
854
                p.reset()
 
855
                p.setup(tb.tb_frame, tb)
 
856
                # Point the debugger at the deepest frame of the stack
 
857
                p.curindex = len(p.stack) - 1
 
858
                p.curframe = p.stack[p.curindex][0]
 
859
                # Start the pdb prompt.
 
860
                p.print_stack_entry(p.stack[p.curindex])
 
861
                p.execRcLines()
 
862
                p.cmdloop()
 
863
            else:
 
864
                pdb.post_mortem(tb)
 
865
        return exitcode
 
866
 
 
867
 
 
868
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
 
869
    from bzrlib.lsprof import profile
 
870
    ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
 
871
    stats.sort()
 
872
    if filename is None:
 
873
        stats.pprint()
 
874
    else:
 
875
        stats.save(filename)
 
876
        trace.note('Profile data written to "%s".', filename)
 
877
    return ret
 
878
 
 
879
 
 
880
def shlex_split_unicode(unsplit):
 
881
    import shlex
 
882
    return [u.decode('utf-8') for u in shlex.split(unsplit.encode('utf-8'))]
 
883
 
 
884
 
 
885
def get_alias(cmd, config=None):
 
886
    """Return an expanded alias, or None if no alias exists.
 
887
 
 
888
    cmd
 
889
        Command to be checked for an alias.
 
890
    config
 
891
        Used to specify an alternative config to use,
 
892
        which is especially useful for testing.
 
893
        If it is unspecified, the global config will be used.
 
894
    """
 
895
    if config is None:
 
896
        import bzrlib.config
 
897
        config = bzrlib.config.GlobalConfig()
 
898
    alias = config.get_alias(cmd)
 
899
    if (alias):
 
900
        return shlex_split_unicode(alias)
 
901
    return None
 
902
 
 
903
 
 
904
def run_bzr(argv):
 
905
    """Execute a command.
 
906
 
 
907
    argv
 
908
       The command-line arguments, without the program name from argv[0]
 
909
       These should already be decoded. All library/test code calling
 
910
       run_bzr should be passing valid strings (don't need decoding).
 
911
 
 
912
    Returns a command status or raises an exception.
 
913
 
 
914
    Special master options: these must come before the command because
 
915
    they control how the command is interpreted.
 
916
 
 
917
    --no-plugins
 
918
        Do not load plugin modules at all
 
919
 
 
920
    --no-aliases
 
921
        Do not allow aliases
 
922
 
 
923
    --builtin
 
924
        Only use builtin commands.  (Plugins are still allowed to change
 
925
        other behaviour.)
 
926
 
 
927
    --profile
 
928
        Run under the Python hotshot profiler.
 
929
 
 
930
    --lsprof
 
931
        Run under the Python lsprof profiler.
 
932
 
 
933
    --coverage
 
934
        Generate line coverage report in the specified directory.
 
935
    """
 
936
    argv = list(argv)
 
937
    trace.mutter("bzr arguments: %r", argv)
 
938
 
 
939
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
 
940
                opt_no_aliases = False
 
941
    opt_lsprof_file = opt_coverage_dir = None
 
942
 
 
943
    # --no-plugins is handled specially at a very early stage. We need
 
944
    # to load plugins before doing other command parsing so that they
 
945
    # can override commands, but this needs to happen first.
 
946
 
 
947
    argv_copy = []
 
948
    i = 0
 
949
    while i < len(argv):
 
950
        a = argv[i]
 
951
        if a == '--profile':
 
952
            opt_profile = True
 
953
        elif a == '--lsprof':
 
954
            opt_lsprof = True
 
955
        elif a == '--lsprof-file':
 
956
            opt_lsprof = True
 
957
            opt_lsprof_file = argv[i + 1]
 
958
            i += 1
 
959
        elif a == '--no-plugins':
 
960
            opt_no_plugins = True
 
961
        elif a == '--no-aliases':
 
962
            opt_no_aliases = True
 
963
        elif a == '--builtin':
 
964
            opt_builtin = True
 
965
        elif a == '--coverage':
 
966
            opt_coverage_dir = argv[i + 1]
 
967
            i += 1
 
968
        elif a.startswith('-D'):
 
969
            debug.debug_flags.add(a[2:])
 
970
        else:
 
971
            argv_copy.append(a)
 
972
        i += 1
 
973
 
 
974
    debug.set_debug_flags_from_config()
 
975
 
 
976
    argv = argv_copy
 
977
    if (not argv):
 
978
        from bzrlib.builtins import cmd_help
 
979
        cmd_help().run_argv_aliases([])
 
980
        return 0
 
981
 
 
982
    if argv[0] == '--version':
 
983
        from bzrlib.builtins import cmd_version
 
984
        cmd_version().run_argv_aliases([])
 
985
        return 0
 
986
 
 
987
    if not opt_no_plugins:
 
988
        from bzrlib.plugin import load_plugins
 
989
        load_plugins()
 
990
    else:
 
991
        from bzrlib.plugin import disable_plugins
 
992
        disable_plugins()
 
993
 
 
994
    alias_argv = None
 
995
 
 
996
    if not opt_no_aliases:
 
997
        alias_argv = get_alias(argv[0])
 
998
        if alias_argv:
 
999
            user_encoding = osutils.get_user_encoding()
 
1000
            alias_argv = [a.decode(user_encoding) for a in alias_argv]
 
1001
            argv[0] = alias_argv.pop(0)
 
1002
 
 
1003
    cmd = argv.pop(0)
 
1004
    # We want only 'ascii' command names, but the user may have typed
 
1005
    # in a Unicode name. In that case, they should just get a
 
1006
    # 'command not found' error later.
 
1007
 
 
1008
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
 
1009
    run = cmd_obj.run_argv_aliases
 
1010
    run_argv = [argv, alias_argv]
 
1011
 
 
1012
    try:
 
1013
        # We can be called recursively (tests for example), but we don't want
 
1014
        # the verbosity level to propagate.
 
1015
        saved_verbosity_level = option._verbosity_level
 
1016
        option._verbosity_level = 0
 
1017
        if opt_lsprof:
 
1018
            if opt_coverage_dir:
 
1019
                trace.warning(
 
1020
                    '--coverage ignored, because --lsprof is in use.')
 
1021
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
 
1022
        elif opt_profile:
 
1023
            if opt_coverage_dir:
 
1024
                trace.warning(
 
1025
                    '--coverage ignored, because --profile is in use.')
 
1026
            ret = apply_profiled(run, *run_argv)
 
1027
        elif opt_coverage_dir:
 
1028
            ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
 
1029
        else:
 
1030
            ret = run(*run_argv)
 
1031
        if 'memory' in debug.debug_flags:
 
1032
            trace.debug_memory('Process status after command:', short=False)
 
1033
        return ret or 0
 
1034
    finally:
 
1035
        # reset, in case we may do other commands later within the same
 
1036
        # process. Commands that want to execute sub-commands must propagate
 
1037
        # --verbose in their own way.
 
1038
        option._verbosity_level = saved_verbosity_level
 
1039
 
 
1040
 
 
1041
def display_command(func):
 
1042
    """Decorator that suppresses pipe/interrupt errors."""
 
1043
    def ignore_pipe(*args, **kwargs):
 
1044
        try:
 
1045
            result = func(*args, **kwargs)
 
1046
            sys.stdout.flush()
 
1047
            return result
 
1048
        except IOError, e:
 
1049
            if getattr(e, 'errno', None) is None:
 
1050
                raise
 
1051
            if e.errno != errno.EPIPE:
 
1052
                # Win32 raises IOError with errno=0 on a broken pipe
 
1053
                if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
 
1054
                    raise
 
1055
            pass
 
1056
        except KeyboardInterrupt:
 
1057
            pass
 
1058
    return ignore_pipe
 
1059
 
 
1060
 
 
1061
def install_bzr_command_hooks():
 
1062
    """Install the hooks to supply bzr's own commands."""
 
1063
    if _list_bzr_commands in Command.hooks["list_commands"]:
 
1064
        return
 
1065
    Command.hooks.install_named_hook("list_commands", _list_bzr_commands,
 
1066
        "bzr commands")
 
1067
    Command.hooks.install_named_hook("get_command", _get_bzr_command,
 
1068
        "bzr commands")
 
1069
    Command.hooks.install_named_hook("get_command", _get_plugin_command,
 
1070
        "bzr plugin commands")
 
1071
    Command.hooks.install_named_hook("get_command", _get_external_command,
 
1072
        "bzr external command lookup")
 
1073
    Command.hooks.install_named_hook("get_missing_command", _try_plugin_provider,
 
1074
        "bzr plugin-provider-db check")
 
1075
 
 
1076
 
 
1077
def main(argv=None):
 
1078
    """Main entry point of command-line interface.
 
1079
 
 
1080
    :param argv: list of unicode command-line arguments similar to sys.argv.
 
1081
        argv[0] is script name usually, it will be ignored.
 
1082
        Don't pass here sys.argv because this list contains plain strings
 
1083
        and not unicode; pass None instead.
 
1084
 
 
1085
    :return: exit code of bzr command.
 
1086
    """
 
1087
    import bzrlib.ui
 
1088
    bzrlib.ui.ui_factory = bzrlib.ui.make_ui_for_terminal(
 
1089
        sys.stdin, sys.stdout, sys.stderr)
 
1090
 
 
1091
    # Is this a final release version? If so, we should suppress warnings
 
1092
    if bzrlib.version_info[3] == 'final':
 
1093
        suppress_deprecation_warnings(override=False)
 
1094
    if argv is None:
 
1095
        argv = osutils.get_unicode_argv()
 
1096
    else:
 
1097
        new_argv = []
 
1098
        try:
 
1099
            # ensure all arguments are unicode strings
 
1100
            for a in argv[1:]:
 
1101
                if isinstance(a, unicode):
 
1102
                    new_argv.append(a)
 
1103
                else:
 
1104
                    new_argv.append(a.decode('ascii'))
 
1105
        except UnicodeDecodeError:
 
1106
            raise errors.BzrError("argv should be list of unicode strings.")
 
1107
        argv = new_argv
 
1108
    ret = run_bzr_catch_errors(argv)
 
1109
    trace.mutter("return code %d", ret)
 
1110
    return ret
 
1111
 
 
1112
 
 
1113
def run_bzr_catch_errors(argv):
 
1114
    """Run a bzr command with parameters as described by argv.
 
1115
 
 
1116
    This function assumed that that UI layer is setup, that symbol deprecations
 
1117
    are already applied, and that unicode decoding has already been performed on argv.
 
1118
    """
 
1119
    install_bzr_command_hooks()
 
1120
    return exception_to_return_code(run_bzr, argv)
 
1121
 
 
1122
 
 
1123
def run_bzr_catch_user_errors(argv):
 
1124
    """Run bzr and report user errors, but let internal errors propagate.
 
1125
 
 
1126
    This is used for the test suite, and might be useful for other programs
 
1127
    that want to wrap the commandline interface.
 
1128
    """
 
1129
    install_bzr_command_hooks()
 
1130
    try:
 
1131
        return run_bzr(argv)
 
1132
    except Exception, e:
 
1133
        if (isinstance(e, (OSError, IOError))
 
1134
            or not getattr(e, 'internal_error', True)):
 
1135
            trace.report_exception(sys.exc_info(), sys.stderr)
 
1136
            return 3
 
1137
        else:
 
1138
            raise
 
1139
 
 
1140
 
 
1141
class HelpCommandIndex(object):
 
1142
    """A index for bzr help that returns commands."""
 
1143
 
 
1144
    def __init__(self):
 
1145
        self.prefix = 'commands/'
 
1146
 
 
1147
    def get_topics(self, topic):
 
1148
        """Search for topic amongst commands.
 
1149
 
 
1150
        :param topic: A topic to search for.
 
1151
        :return: A list which is either empty or contains a single
 
1152
            Command entry.
 
1153
        """
 
1154
        if topic and topic.startswith(self.prefix):
 
1155
            topic = topic[len(self.prefix):]
 
1156
        try:
 
1157
            cmd = _get_cmd_object(topic)
 
1158
        except KeyError:
 
1159
            return []
 
1160
        else:
 
1161
            return [cmd]
 
1162
 
 
1163
 
 
1164
class Provider(object):
 
1165
    '''Generic class to be overriden by plugins'''
 
1166
 
 
1167
    def plugin_for_command(self, cmd_name):
 
1168
        '''Takes a command and returns the information for that plugin
 
1169
 
 
1170
        :return: A dictionary with all the available information
 
1171
        for the requested plugin
 
1172
        '''
 
1173
        raise NotImplementedError
 
1174
 
 
1175
 
 
1176
class ProvidersRegistry(registry.Registry):
 
1177
    '''This registry exists to allow other providers to exist'''
 
1178
 
 
1179
    def __iter__(self):
 
1180
        for key, provider in self.iteritems():
 
1181
            yield provider
 
1182
 
 
1183
command_providers_registry = ProvidersRegistry()
 
1184
 
 
1185
 
 
1186
if __name__ == '__main__':
 
1187
    sys.exit(main(sys.argv))