/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2009-06-10 03:31:01 UTC
  • mfrom: (4070.12.3 249908-doc-generate)
  • mto: This revision was merged to the branch mainline in revision 4464.
  • Revision ID: mbp@sourcefrog.net-20090610033101-ce26xd79i9cbmpsd
Merge other outstanding work on 249908

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