~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Robert Collins
  • Date: 2006-05-16 06:45:43 UTC
  • mto: (1713.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 1714.
  • Revision ID: robertc@robertcollins.net-20060516064543-5cb7cc63047ba98b
Start on bench_add, an add benchtest.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
 
1
# Copyright (C) 2006 by Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
28
28
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
29
29
# the profile output behind so it can be interactively examined?
30
30
 
 
31
import sys
31
32
import os
32
 
import sys
33
 
 
34
 
from bzrlib.lazy_import import lazy_import
35
 
lazy_import(globals(), """
36
 
import codecs
 
33
from warnings import warn
37
34
import errno
38
 
from warnings import warn
39
35
 
40
36
import bzrlib
41
 
from bzrlib import (
42
 
    debug,
43
 
    errors,
44
 
    option,
45
 
    osutils,
46
 
    trace,
47
 
    win32utils,
48
 
    )
49
 
""")
50
 
 
51
 
from bzrlib import registry
52
 
# Compatibility
 
37
from bzrlib.errors import (BzrError,
 
38
                           BzrCheckError,
 
39
                           BzrCommandError,
 
40
                           BzrOptionError,
 
41
                           NotBranchError)
53
42
from bzrlib.option import Option
54
 
 
 
43
from bzrlib.revisionspec import RevisionSpec
 
44
from bzrlib.symbol_versioning import *
 
45
import bzrlib.trace
 
46
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
55
47
 
56
48
plugin_cmds = {}
57
49
 
70
62
        k_unsquished = _unsquish_command_name(k)
71
63
    else:
72
64
        k_unsquished = k
73
 
    if k_unsquished not in plugin_cmds:
 
65
    if not plugin_cmds.has_key(k_unsquished):
74
66
        plugin_cmds[k_unsquished] = cmd
75
 
        ## trace.mutter('registered plugin command %s', k_unsquished)
 
67
        mutter('registered plugin command %s', k_unsquished)
76
68
        if decorate and k_unsquished in builtin_command_names():
77
69
            return _builtin_commands()[k_unsquished]
78
70
    elif decorate:
80
72
        plugin_cmds[k_unsquished] = cmd
81
73
        return result
82
74
    else:
83
 
        trace.log_error('Two plugins defined the same command: %r' % k)
84
 
        trace.log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
85
 
        trace.log_error('Previously this command was registered from %r' %
86
 
                        sys.modules[plugin_cmds[k_unsquished].__module__])
 
75
        log_error('Two plugins defined the same command: %r' % k)
 
76
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
87
77
 
88
78
 
89
79
def _squish_command_name(cmd):
91
81
 
92
82
 
93
83
def _unsquish_command_name(cmd):
 
84
    assert cmd.startswith("cmd_")
94
85
    return cmd[4:].replace('_','-')
95
86
 
96
87
 
134
125
    plugins_override
135
126
        If true, plugin commands can override builtins.
136
127
    """
137
 
    try:
138
 
        return _get_cmd_object(cmd_name, plugins_override)
139
 
    except KeyError:
140
 
        raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
141
 
 
142
 
 
143
 
def _get_cmd_object(cmd_name, plugins_override=True):
144
 
    """Worker for get_cmd_object which raises KeyError rather than BzrCommandError."""
145
128
    from bzrlib.externalcommand import ExternalCommand
146
129
 
147
 
    # We want only 'ascii' command names, but the user may have typed
148
 
    # in a Unicode name. In that case, they should just get a
149
 
    # 'command not found' error later.
150
 
    # In the future, we may actually support Unicode command names.
 
130
    cmd_name = str(cmd_name)            # not unicode
151
131
 
152
132
    # first look up this command under the specified name
153
133
    cmds = _get_cmd_dict(plugins_override=plugins_override)
165
145
    if cmd_obj:
166
146
        return cmd_obj
167
147
 
168
 
    # look for plugins that provide this command but aren't installed
169
 
    for provider in command_providers_registry:
170
 
        try:
171
 
            plugin_metadata = provider.plugin_for_command(cmd_name)
172
 
        except errors.NoPluginAvailable:
173
 
            pass
174
 
        else:
175
 
            raise errors.CommandAvailableInPlugin(cmd_name, 
176
 
                                                  plugin_metadata, provider)
177
 
 
178
 
    raise KeyError
 
148
    raise BzrCommandError("unknown command %r" % cmd_name)
179
149
 
180
150
 
181
151
class Command(object):
219
189
    hidden
220
190
        If true, this command isn't advertised.  This is typically
221
191
        for commands intended for expert users.
222
 
 
223
 
    encoding_type
224
 
        Command objects will get a 'outf' attribute, which has been
225
 
        setup to properly handle encoding of unicode strings.
226
 
        encoding_type determines what will happen when characters cannot
227
 
        be encoded
228
 
            strict - abort if we cannot decode
229
 
            replace - put in a bogus character (typically '?')
230
 
            exact - do not encode sys.stdout
231
 
 
232
 
            NOTE: by default on Windows, sys.stdout is opened as a text
233
 
            stream, therefore LF line-endings are converted to CRLF.
234
 
            When a command uses encoding_type = 'exact', then
235
 
            sys.stdout is forced to be a binary stream, and line-endings
236
 
            will not mangled.
237
 
 
238
192
    """
239
193
    aliases = []
240
194
    takes_args = []
241
195
    takes_options = []
242
 
    encoding_type = 'strict'
243
196
 
244
197
    hidden = False
245
198
    
247
200
        """Construct an instance of this command."""
248
201
        if self.__doc__ == Command.__doc__:
249
202
            warn("No help message set for %r" % self)
250
 
        # List of standard options directly supported
251
 
        self.supported_std_options = []
252
 
 
253
 
    def _maybe_expand_globs(self, file_list):
254
 
        """Glob expand file_list if the platform does not do that itself.
255
 
        
256
 
        :return: A possibly empty list of unicode paths.
257
 
 
258
 
        Introduced in bzrlib 0.18.
259
 
        """
260
 
        if not file_list:
261
 
            file_list = []
262
 
        if sys.platform == 'win32':
263
 
            file_list = win32utils.glob_expand(file_list)
264
 
        return list(file_list)
265
 
 
266
 
    def _usage(self):
267
 
        """Return single-line grammar for this command.
268
 
 
269
 
        Only describes arguments, not options.
270
 
        """
271
 
        s = 'bzr ' + self.name() + ' '
272
 
        for aname in self.takes_args:
273
 
            aname = aname.upper()
274
 
            if aname[-1] in ['$', '+']:
275
 
                aname = aname[:-1] + '...'
276
 
            elif aname[-1] == '?':
277
 
                aname = '[' + aname[:-1] + ']'
278
 
            elif aname[-1] == '*':
279
 
                aname = '[' + aname[:-1] + '...]'
280
 
            s += aname + ' '
281
 
        s = s[:-1]      # remove last space
282
 
        return s
283
 
 
284
 
    def get_help_text(self, additional_see_also=None, plain=True,
285
 
                      see_also_as_links=False):
286
 
        """Return a text string with help for this command.
287
 
        
288
 
        :param additional_see_also: Additional help topics to be
289
 
            cross-referenced.
290
 
        :param plain: if False, raw help (reStructuredText) is
291
 
            returned instead of plain text.
292
 
        :param see_also_as_links: if True, convert items in 'See also'
293
 
            list to internal links (used by bzr_man rstx generator)
294
 
        """
295
 
        doc = self.help()
296
 
        if doc is None:
297
 
            raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
298
 
 
299
 
        # Extract the summary (purpose) and sections out from the text
300
 
        purpose,sections = self._get_help_parts(doc)
301
 
 
302
 
        # If a custom usage section was provided, use it
303
 
        if sections.has_key('Usage'):
304
 
            usage = sections.pop('Usage')
305
 
        else:
306
 
            usage = self._usage()
307
 
 
308
 
        # The header is the purpose and usage
309
 
        result = ""
310
 
        result += ':Purpose: %s\n' % purpose
311
 
        if usage.find('\n') >= 0:
312
 
            result += ':Usage:\n%s\n' % usage
313
 
        else:
314
 
            result += ':Usage:   %s\n' % usage
315
 
        result += '\n'
316
 
 
317
 
        # Add the options
318
 
        options = option.get_optparser(self.options()).format_option_help()
319
 
        if options.startswith('Options:'):
320
 
            result += ':' + options
321
 
        elif options.startswith('options:'):
322
 
            # Python 2.4 version of optparse
323
 
            result += ':Options:' + options[len('options:'):]
324
 
        else:
325
 
            result += options
326
 
        result += '\n'
327
 
 
328
 
        # Add the description, indenting it 2 spaces
329
 
        # to match the indentation of the options
330
 
        if sections.has_key(None):
331
 
            text = sections.pop(None)
332
 
            text = '\n  '.join(text.splitlines())
333
 
            result += ':%s:\n  %s\n\n' % ('Description',text)
334
 
 
335
 
        # Add the custom sections (e.g. Examples). Note that there's no need
336
 
        # to indent these as they must be indented already in the source.
337
 
        if sections:
338
 
            labels = sorted(sections.keys())
339
 
            for label in labels:
340
 
                result += ':%s:\n%s\n\n' % (label,sections[label])
341
 
 
342
 
        # Add the aliases, source (plug-in) and see also links, if any
343
 
        if self.aliases:
344
 
            result += ':Aliases:  '
345
 
            result += ', '.join(self.aliases) + '\n'
346
 
        plugin_name = self.plugin_name()
347
 
        if plugin_name is not None:
348
 
            result += ':From:     plugin "%s"\n' % plugin_name
349
 
        see_also = self.get_see_also(additional_see_also)
350
 
        if see_also:
351
 
            if not plain and see_also_as_links:
352
 
                see_also_links = []
353
 
                for item in see_also:
354
 
                    if item == 'topics':
355
 
                        # topics doesn't have an independent section
356
 
                        # so don't create a real link
357
 
                        see_also_links.append(item)
358
 
                    else:
359
 
                        # Use a reST link for this entry
360
 
                        see_also_links.append("`%s`_" % (item,))
361
 
                see_also = see_also_links
362
 
            result += ':See also: '
363
 
            result += ', '.join(see_also) + '\n'
364
 
 
365
 
        # If this will be rendered as plain text, convert it
366
 
        if plain:
367
 
            import bzrlib.help_topics
368
 
            result = bzrlib.help_topics.help_as_plain_text(result)
369
 
        return result
370
 
 
371
 
    @staticmethod
372
 
    def _get_help_parts(text):
373
 
        """Split help text into a summary and named sections.
374
 
 
375
 
        :return: (summary,sections) where summary is the top line and
376
 
            sections is a dictionary of the rest indexed by section name.
377
 
            A section starts with a heading line of the form ":xxx:".
378
 
            Indented text on following lines is the section value.
379
 
            All text found outside a named section is assigned to the
380
 
            default section which is given the key of None.
381
 
        """
382
 
        def save_section(sections, label, section):
383
 
            if len(section) > 0:
384
 
                if sections.has_key(label):
385
 
                    sections[label] += '\n' + section
386
 
                else:
387
 
                    sections[label] = section
388
 
 
389
 
        lines = text.rstrip().splitlines()
390
 
        summary = lines.pop(0)
391
 
        sections = {}
392
 
        label,section = None,''
393
 
        for line in lines:
394
 
            if line.startswith(':') and line.endswith(':') and len(line) > 2:
395
 
                save_section(sections, label, section)
396
 
                label,section = line[1:-1],''
397
 
            elif (label is not None) and len(line) > 1 and not line[0].isspace():
398
 
                save_section(sections, label, section)
399
 
                label,section = None,line
400
 
            else:
401
 
                if len(section) > 0:
402
 
                    section += '\n' + line
403
 
                else:
404
 
                    section = line
405
 
        save_section(sections, label, section)
406
 
        return summary, sections
407
 
 
408
 
    def get_help_topic(self):
409
 
        """Return the commands help topic - its name."""
410
 
        return self.name()
411
 
 
412
 
    def get_see_also(self, additional_terms=None):
413
 
        """Return a list of help topics that are related to this command.
414
 
        
415
 
        The list is derived from the content of the _see_also attribute. Any
416
 
        duplicates are removed and the result is in lexical order.
417
 
        :param additional_terms: Additional help topics to cross-reference.
418
 
        :return: A list of help topics.
419
 
        """
420
 
        see_also = set(getattr(self, '_see_also', []))
421
 
        if additional_terms:
422
 
            see_also.update(additional_terms)
423
 
        return sorted(see_also)
424
203
 
425
204
    def options(self):
426
205
        """Return dict of valid options for this command.
427
206
 
428
207
        Maps from long option name to option object."""
429
 
        r = Option.STD_OPTIONS.copy()
430
 
        std_names = r.keys()
 
208
        r = dict()
 
209
        r['help'] = Option.OPTIONS['help']
431
210
        for o in self.takes_options:
432
 
            if isinstance(o, basestring):
433
 
                o = option.Option.OPTIONS[o]
 
211
            if not isinstance(o, Option):
 
212
                o = Option.OPTIONS[o]
434
213
            r[o.name] = o
435
 
            if o.name in std_names:
436
 
                self.supported_std_options.append(o.name)
437
214
        return r
438
215
 
439
 
    def _setup_outf(self):
440
 
        """Return a file linked to stdout, which has proper encoding."""
441
 
        # Originally I was using self.stdout, but that looks
442
 
        # *way* too much like sys.stdout
443
 
        if self.encoding_type == 'exact':
444
 
            # force sys.stdout to be binary stream on win32
445
 
            if sys.platform == 'win32':
446
 
                fileno = getattr(sys.stdout, 'fileno', None)
447
 
                if fileno:
448
 
                    import msvcrt
449
 
                    msvcrt.setmode(fileno(), os.O_BINARY)
450
 
            self.outf = sys.stdout
451
 
            return
452
 
 
453
 
        output_encoding = osutils.get_terminal_encoding()
454
 
 
455
 
        self.outf = codecs.getwriter(output_encoding)(sys.stdout,
456
 
                        errors=self.encoding_type)
457
 
        # For whatever reason codecs.getwriter() does not advertise its encoding
458
 
        # it just returns the encoding of the wrapped file, which is completely
459
 
        # bogus. So set the attribute, so we can find the correct encoding later.
460
 
        self.outf.encoding = output_encoding
 
216
    @deprecated_method(zero_eight)
 
217
    def run_argv(self, argv):
 
218
        """Parse command line and run.
 
219
        
 
220
        See run_argv_aliases for the 0.8 and beyond api.
 
221
        """
 
222
        return self.run_argv_aliases(argv)
461
223
 
462
224
    def run_argv_aliases(self, argv, alias_argv=None):
463
225
        """Parse the command line and run with extra aliases in alias_argv."""
464
 
        if argv is None:
465
 
            warn("Passing None for [] is deprecated from bzrlib 0.10",
466
 
                 DeprecationWarning, stacklevel=2)
467
 
            argv = []
468
226
        args, opts = parse_args(self, argv, alias_argv)
469
 
 
470
 
        # Process the standard options
471
227
        if 'help' in opts:  # e.g. bzr add --help
472
 
            sys.stdout.write(self.get_help_text())
 
228
            from bzrlib.help import help_on_command
 
229
            help_on_command(self.name())
473
230
            return 0
474
 
        trace.set_verbosity_level(option._verbosity_level)
475
 
        if 'verbose' in self.supported_std_options:
476
 
            opts['verbose'] = trace.is_verbose()
477
 
        elif opts.has_key('verbose'):
478
 
            del opts['verbose']
479
 
        if 'quiet' in self.supported_std_options:
480
 
            opts['quiet'] = trace.is_quiet()
481
 
        elif opts.has_key('quiet'):
482
 
            del opts['quiet']
483
 
 
 
231
        # XXX: This should be handled by the parser
 
232
        allowed_names = self.options().keys()
 
233
        for oname in opts:
 
234
            if oname not in allowed_names:
 
235
                raise BzrCommandError("option '--%s' is not allowed for"
 
236
                                      " command %r" % (oname, self.name()))
484
237
        # mix arguments and options into one dictionary
485
238
        cmdargs = _match_argform(self.name(), self.takes_args, args)
486
239
        cmdopts = {}
490
243
        all_cmd_args = cmdargs.copy()
491
244
        all_cmd_args.update(cmdopts)
492
245
 
493
 
        self._setup_outf()
494
 
 
495
246
        return self.run(**all_cmd_args)
496
 
 
 
247
    
497
248
    def run(self):
498
249
        """Actually run the command.
499
250
 
504
255
        shell error code if not.  It's OK for this method to allow
505
256
        an exception to raise up.
506
257
        """
507
 
        raise NotImplementedError('no implementation of command %r'
 
258
        raise NotImplementedError('no implementation of command %r' 
508
259
                                  % self.name())
509
260
 
510
261
    def help(self):
517
268
    def name(self):
518
269
        return _unsquish_command_name(self.__class__.__name__)
519
270
 
520
 
    def plugin_name(self):
521
 
        """Get the name of the plugin that provides this command.
522
271
 
523
 
        :return: The name of the plugin or None if the command is builtin.
524
 
        """
525
 
        mod_parts = self.__module__.split('.')
526
 
        if len(mod_parts) >= 3 and mod_parts[1] == 'plugins':
527
 
            return mod_parts[2]
 
272
def parse_spec(spec):
 
273
    """
 
274
    >>> parse_spec(None)
 
275
    [None, None]
 
276
    >>> parse_spec("./")
 
277
    ['./', None]
 
278
    >>> parse_spec("../@")
 
279
    ['..', -1]
 
280
    >>> parse_spec("../f/@35")
 
281
    ['../f', 35]
 
282
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
283
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
 
284
    """
 
285
    if spec is None:
 
286
        return [None, None]
 
287
    if '/@' in spec:
 
288
        parsed = spec.split('/@')
 
289
        assert len(parsed) == 2
 
290
        if parsed[1] == "":
 
291
            parsed[1] = -1
528
292
        else:
529
 
            return None
530
 
 
 
293
            try:
 
294
                parsed[1] = int(parsed[1])
 
295
            except ValueError:
 
296
                pass # We can allow stuff like ./@revid:blahblahblah
 
297
            else:
 
298
                assert parsed[1] >=0
 
299
    else:
 
300
        parsed = [spec, None]
 
301
    return parsed
531
302
 
532
303
def parse_args(command, argv, alias_argv=None):
533
304
    """Parse command line.
537
308
    lookup table, something about the available options, what optargs
538
309
    they take, and which commands will accept them.
539
310
    """
540
 
    # TODO: make it a method of the Command?
541
 
    parser = option.get_optparser(command.options())
542
 
    if alias_argv is not None:
543
 
        args = alias_argv + argv
544
 
    else:
545
 
        args = argv
546
 
 
547
 
    options, args = parser.parse_args(args)
548
 
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
549
 
                 v is not option.OptionParser.DEFAULT_VALUE])
 
311
    # TODO: chop up this beast; make it a method of the Command
 
312
    args = []
 
313
    opts = {}
 
314
    alias_opts = {}
 
315
 
 
316
    cmd_options = command.options()
 
317
    argsover = False
 
318
    proc_aliasarg = True # Are we processing alias_argv now?
 
319
    for proc_argv in alias_argv, argv:
 
320
        while proc_argv:
 
321
            a = proc_argv.pop(0)
 
322
            if argsover:
 
323
                args.append(a)
 
324
                continue
 
325
            elif a == '--':
 
326
                # We've received a standalone -- No more flags
 
327
                argsover = True
 
328
                continue
 
329
            if a[0] == '-':
 
330
                # option names must not be unicode
 
331
                a = str(a)
 
332
                optarg = None
 
333
                if a[1] == '-':
 
334
                    mutter("  got option %r", a)
 
335
                    if '=' in a:
 
336
                        optname, optarg = a[2:].split('=', 1)
 
337
                    else:
 
338
                        optname = a[2:]
 
339
                    if optname not in cmd_options:
 
340
                        raise BzrOptionError('unknown long option %r for'
 
341
                                             ' command %s' % 
 
342
                                             (a, command.name()))
 
343
                else:
 
344
                    shortopt = a[1:]
 
345
                    if shortopt in Option.SHORT_OPTIONS:
 
346
                        # Multi-character options must have a space to delimit
 
347
                        # their value
 
348
                        # ^^^ what does this mean? mbp 20051014
 
349
                        optname = Option.SHORT_OPTIONS[shortopt].name
 
350
                    else:
 
351
                        # Single character short options, can be chained,
 
352
                        # and have their value appended to their name
 
353
                        shortopt = a[1:2]
 
354
                        if shortopt not in Option.SHORT_OPTIONS:
 
355
                            # We didn't find the multi-character name, and we
 
356
                            # didn't find the single char name
 
357
                            raise BzrError('unknown short option %r' % a)
 
358
                        optname = Option.SHORT_OPTIONS[shortopt].name
 
359
 
 
360
                        if a[2:]:
 
361
                            # There are extra things on this option
 
362
                            # see if it is the value, or if it is another
 
363
                            # short option
 
364
                            optargfn = Option.OPTIONS[optname].type
 
365
                            if optargfn is None:
 
366
                                # This option does not take an argument, so the
 
367
                                # next entry is another short option, pack it
 
368
                                # back into the list
 
369
                                proc_argv.insert(0, '-' + a[2:])
 
370
                            else:
 
371
                                # This option takes an argument, so pack it
 
372
                                # into the array
 
373
                                optarg = a[2:]
 
374
                
 
375
                    if optname not in cmd_options:
 
376
                        raise BzrOptionError('unknown short option %r for'
 
377
                                             ' command %s' % 
 
378
                                             (shortopt, command.name()))
 
379
                if optname in opts:
 
380
                    # XXX: Do we ever want to support this, e.g. for -r?
 
381
                    if proc_aliasarg:
 
382
                        raise BzrError('repeated option %r' % a)
 
383
                    elif optname in alias_opts:
 
384
                        # Replace what's in the alias with what's in the real
 
385
                        # argument
 
386
                        del alias_opts[optname]
 
387
                        del opts[optname]
 
388
                        proc_argv.insert(0, a)
 
389
                        continue
 
390
                    else:
 
391
                        raise BzrError('repeated option %r' % a)
 
392
                    
 
393
                option_obj = cmd_options[optname]
 
394
                optargfn = option_obj.type
 
395
                if optargfn:
 
396
                    if optarg == None:
 
397
                        if not proc_argv:
 
398
                            raise BzrError('option %r needs an argument' % a)
 
399
                        else:
 
400
                            optarg = proc_argv.pop(0)
 
401
                    opts[optname] = optargfn(optarg)
 
402
                    if proc_aliasarg:
 
403
                        alias_opts[optname] = optargfn(optarg)
 
404
                else:
 
405
                    if optarg != None:
 
406
                        raise BzrError('option %r takes no argument' % optname)
 
407
                    opts[optname] = True
 
408
                    if proc_aliasarg:
 
409
                        alias_opts[optname] = True
 
410
            else:
 
411
                args.append(a)
 
412
        proc_aliasarg = False # Done with alias argv
550
413
    return args, opts
551
414
 
552
415
 
567
430
                argdict[argname + '_list'] = None
568
431
        elif ap[-1] == '+':
569
432
            if not args:
570
 
                raise errors.BzrCommandError("command %r needs one or more %s"
571
 
                                             % (cmd, argname.upper()))
 
433
                raise BzrCommandError("command %r needs one or more %s"
 
434
                        % (cmd, argname.upper()))
572
435
            else:
573
436
                argdict[argname + '_list'] = args[:]
574
437
                args = []
575
438
        elif ap[-1] == '$': # all but one
576
439
            if len(args) < 2:
577
 
                raise errors.BzrCommandError("command %r needs one or more %s"
578
 
                                             % (cmd, argname.upper()))
 
440
                raise BzrCommandError("command %r needs one or more %s"
 
441
                        % (cmd, argname.upper()))
579
442
            argdict[argname + '_list'] = args[:-1]
580
 
            args[:-1] = []
 
443
            args[:-1] = []                
581
444
        else:
582
445
            # just a plain arg
583
446
            argname = ap
584
447
            if not args:
585
 
                raise errors.BzrCommandError("command %r requires argument %s"
586
 
                               % (cmd, argname.upper()))
 
448
                raise BzrCommandError("command %r requires argument %s"
 
449
                        % (cmd, argname.upper()))
587
450
            else:
588
451
                argdict[argname] = args.pop(0)
589
452
            
590
453
    if args:
591
 
        raise errors.BzrCommandError("extra argument to command %s: %s"
592
 
                                     % (cmd, args[0]))
 
454
        raise BzrCommandError("extra argument to command %s: %s"
 
455
                              % (cmd, args[0]))
593
456
 
594
457
    return argdict
595
458
 
596
 
def apply_coveraged(dirname, the_callable, *args, **kwargs):
597
 
    # Cannot use "import trace", as that would import bzrlib.trace instead of
598
 
    # the standard library's trace.
599
 
    trace = __import__('trace')
600
 
 
601
 
    tracer = trace.Trace(count=1, trace=0)
602
 
    sys.settrace(tracer.globaltrace)
603
 
 
604
 
    ret = the_callable(*args, **kwargs)
605
 
 
606
 
    sys.settrace(None)
607
 
    results = tracer.results()
608
 
    results.write_results(show_missing=1, summary=False,
609
 
                          coverdir=dirname)
610
459
 
611
460
 
612
461
def apply_profiled(the_callable, *args, **kwargs):
634
483
 
635
484
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
636
485
    from bzrlib.lsprof import profile
 
486
    import cPickle
637
487
    ret, stats = profile(the_callable, *args, **kwargs)
638
488
    stats.sort()
639
489
    if filename is None:
640
490
        stats.pprint()
641
491
    else:
642
 
        stats.save(filename)
643
 
        trace.note('Profile data written to "%s".', filename)
 
492
        stats.freeze()
 
493
        cPickle.dump(stats, open(filename, 'w'), 2)
 
494
        print 'Profile data written to %r.' % filename
644
495
    return ret
645
496
 
646
497
 
647
 
def shlex_split_unicode(unsplit):
648
 
    import shlex
649
 
    return [u.decode('utf-8') for u in shlex.split(unsplit.encode('utf-8'))]
650
 
 
651
 
 
652
 
def get_alias(cmd, config=None):
653
 
    """Return an expanded alias, or None if no alias exists.
654
 
 
655
 
    cmd
656
 
        Command to be checked for an alias.
657
 
    config
658
 
        Used to specify an alternative config to use,
659
 
        which is especially useful for testing.
660
 
        If it is unspecified, the global config will be used.
661
 
    """
662
 
    if config is None:
663
 
        import bzrlib.config
664
 
        config = bzrlib.config.GlobalConfig()
665
 
    alias = config.get_alias(cmd)
 
498
def get_alias(cmd):
 
499
    """Return an expanded alias, or None if no alias exists"""
 
500
    import bzrlib.config
 
501
    alias = bzrlib.config.GlobalConfig().get_alias(cmd)
666
502
    if (alias):
667
 
        return shlex_split_unicode(alias)
 
503
        return alias.split(' ')
668
504
    return None
669
505
 
670
506
 
671
507
def run_bzr(argv):
672
508
    """Execute a command.
673
509
 
 
510
    This is similar to main(), but without all the trappings for
 
511
    logging and error handling.  
 
512
    
674
513
    argv
675
514
       The command-line arguments, without the program name from argv[0]
676
 
       These should already be decoded. All library/test code calling
677
 
       run_bzr should be passing valid strings (don't need decoding).
678
515
    
679
516
    Returns a command status or raises an exception.
680
517
 
696
533
 
697
534
    --lsprof
698
535
        Run under the Python lsprof profiler.
699
 
 
700
 
    --coverage
701
 
        Generate line coverage report in the specified directory.
702
536
    """
703
 
    argv = list(argv)
704
 
    trace.mutter("bzr arguments: %r", argv)
 
537
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
705
538
 
706
539
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
707
540
                opt_no_aliases = False
708
 
    opt_lsprof_file = opt_coverage_dir = None
 
541
    opt_lsprof_file = None
709
542
 
710
543
    # --no-plugins is handled specially at a very early stage. We need
711
544
    # to load plugins before doing other command parsing so that they
720
553
        elif a == '--lsprof':
721
554
            opt_lsprof = True
722
555
        elif a == '--lsprof-file':
723
 
            opt_lsprof = True
724
556
            opt_lsprof_file = argv[i + 1]
725
557
            i += 1
726
558
        elif a == '--no-plugins':
729
561
            opt_no_aliases = True
730
562
        elif a == '--builtin':
731
563
            opt_builtin = True
732
 
        elif a == '--coverage':
733
 
            opt_coverage_dir = argv[i + 1]
734
 
            i += 1
735
 
        elif a.startswith('-D'):
736
 
            debug.debug_flags.add(a[2:])
 
564
        elif a in ('--quiet', '-q'):
 
565
            be_quiet()
737
566
        else:
738
567
            argv_copy.append(a)
739
568
        i += 1
745
574
        return 0
746
575
 
747
576
    if argv[0] == '--version':
748
 
        from bzrlib.builtins import cmd_version
749
 
        cmd_version().run_argv_aliases([])
 
577
        from bzrlib.builtins import show_version
 
578
        show_version()
750
579
        return 0
751
 
 
 
580
        
752
581
    if not opt_no_plugins:
753
582
        from bzrlib.plugin import load_plugins
754
583
        load_plugins()
761
590
    if not opt_no_aliases:
762
591
        alias_argv = get_alias(argv[0])
763
592
        if alias_argv:
764
 
            user_encoding = osutils.get_user_encoding()
765
 
            alias_argv = [a.decode(user_encoding) for a in alias_argv]
 
593
            alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
766
594
            argv[0] = alias_argv.pop(0)
767
595
 
768
 
    cmd = argv.pop(0)
769
 
    # We want only 'ascii' command names, but the user may have typed
770
 
    # in a Unicode name. In that case, they should just get a
771
 
    # 'command not found' error later.
 
596
    cmd = str(argv.pop(0))
772
597
 
773
598
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
774
 
    run = cmd_obj.run_argv_aliases
775
 
    run_argv = [argv, alias_argv]
 
599
    if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
 
600
        run = cmd_obj.run_argv
 
601
        run_argv = [argv]
 
602
    else:
 
603
        run = cmd_obj.run_argv_aliases
 
604
        run_argv = [argv, alias_argv]
776
605
 
777
606
    try:
778
 
        # We can be called recursively (tests for example), but we don't want
779
 
        # the verbosity level to propagate.
780
 
        saved_verbosity_level = option._verbosity_level
781
 
        option._verbosity_level = 0
782
607
        if opt_lsprof:
783
 
            if opt_coverage_dir:
784
 
                trace.warning(
785
 
                    '--coverage ignored, because --lsprof is in use.')
786
608
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
787
609
        elif opt_profile:
788
 
            if opt_coverage_dir:
789
 
                trace.warning(
790
 
                    '--coverage ignored, because --profile is in use.')
791
610
            ret = apply_profiled(run, *run_argv)
792
 
        elif opt_coverage_dir:
793
 
            ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
794
611
        else:
795
612
            ret = run(*run_argv)
796
 
        if 'memory' in debug.debug_flags:
797
 
            trace.debug_memory('Process status after command:', short=False)
798
613
        return ret or 0
799
614
    finally:
800
 
        # reset, in case we may do other commands later within the same
801
 
        # process. Commands that want to execute sub-commands must propagate
802
 
        # --verbose in their own way.
803
 
        option._verbosity_level = saved_verbosity_level
 
615
        # reset, in case we may do other commands later within the same process
 
616
        be_quiet(False)
804
617
 
805
618
def display_command(func):
806
619
    """Decorator that suppresses pipe/interrupt errors."""
810
623
            sys.stdout.flush()
811
624
            return result
812
625
        except IOError, e:
813
 
            if getattr(e, 'errno', None) is None:
 
626
            if not hasattr(e, 'errno'):
814
627
                raise
815
628
            if e.errno != errno.EPIPE:
816
 
                # Win32 raises IOError with errno=0 on a broken pipe
817
 
                if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
818
 
                    raise
 
629
                raise
819
630
            pass
820
631
        except KeyboardInterrupt:
821
632
            pass
825
636
def main(argv):
826
637
    import bzrlib.ui
827
638
    from bzrlib.ui.text import TextUIFactory
 
639
    ## bzrlib.trace.enable_default_logging()
 
640
    bzrlib.trace.log_startup(argv)
828
641
    bzrlib.ui.ui_factory = TextUIFactory()
829
 
 
830
 
    # Is this a final release version? If so, we should suppress warnings
831
 
    if bzrlib.version_info[3] == 'final':
832
 
        from bzrlib import symbol_versioning
833
 
        symbol_versioning.suppress_deprecation_warnings(override=False)
834
 
    try:
835
 
        user_encoding = osutils.get_user_encoding()
836
 
        argv = [a.decode(user_encoding) for a in argv[1:]]
837
 
    except UnicodeDecodeError:
838
 
        raise errors.BzrError(("Parameter '%r' is unsupported by the current "
839
 
                                                            "encoding." % a))
840
 
    ret = run_bzr_catch_errors(argv)
841
 
    trace.mutter("return code %d", ret)
 
642
    ret = run_bzr_catch_errors(argv[1:])
 
643
    mutter("return code %d", ret)
842
644
    return ret
843
645
 
844
646
 
845
647
def run_bzr_catch_errors(argv):
846
 
    # Note: The except clause logic below should be kept in sync with the
847
 
    # profile() routine in lsprof.py.
848
648
    try:
849
 
        return run_bzr(argv)
850
 
    except (KeyboardInterrupt, Exception), e:
 
649
        try:
 
650
            return run_bzr(argv)
 
651
        finally:
 
652
            # do this here inside the exception wrappers to catch EPIPE
 
653
            sys.stdout.flush()
 
654
    except Exception, e:
851
655
        # used to handle AssertionError and KeyboardInterrupt
852
656
        # specially here, but hopefully they're handled ok by the logger now
853
 
        exitcode = trace.report_exception(sys.exc_info(), sys.stderr)
854
 
        if os.environ.get('BZR_PDB'):
855
 
            print '**** entering debugger'
856
 
            import pdb
857
 
            pdb.post_mortem(sys.exc_traceback)
858
 
        return exitcode
859
 
 
860
 
 
861
 
def run_bzr_catch_user_errors(argv):
862
 
    """Run bzr and report user errors, but let internal errors propagate.
863
 
 
864
 
    This is used for the test suite, and might be useful for other programs
865
 
    that want to wrap the commandline interface.
866
 
    """
867
 
    try:
868
 
        return run_bzr(argv)
869
 
    except Exception, e:
870
 
        if (isinstance(e, (OSError, IOError))
871
 
            or not getattr(e, 'internal_error', True)):
872
 
            trace.report_exception(sys.exc_info(), sys.stderr)
873
 
            return 3
874
 
        else:
875
 
            raise
876
 
 
877
 
 
878
 
class HelpCommandIndex(object):
879
 
    """A index for bzr help that returns commands."""
880
 
 
881
 
    def __init__(self):
882
 
        self.prefix = 'commands/'
883
 
 
884
 
    def get_topics(self, topic):
885
 
        """Search for topic amongst commands.
886
 
 
887
 
        :param topic: A topic to search for.
888
 
        :return: A list which is either empty or contains a single
889
 
            Command entry.
890
 
        """
891
 
        if topic and topic.startswith(self.prefix):
892
 
            topic = topic[len(self.prefix):]
893
 
        try:
894
 
            cmd = _get_cmd_object(topic)
895
 
        except KeyError:
896
 
            return []
897
 
        else:
898
 
            return [cmd]
899
 
 
900
 
 
901
 
class Provider(object):
902
 
    '''Generic class to be overriden by plugins'''
903
 
 
904
 
    def plugin_for_command(self, cmd_name):
905
 
        '''Takes a command and returns the information for that plugin
906
 
        
907
 
        :return: A dictionary with all the available information 
908
 
        for the requested plugin
909
 
        '''
910
 
        raise NotImplementedError
911
 
 
912
 
 
913
 
class ProvidersRegistry(registry.Registry):
914
 
    '''This registry exists to allow other providers to exist'''
915
 
 
916
 
    def __iter__(self):
917
 
        for key, provider in self.iteritems():
918
 
            yield provider
919
 
 
920
 
command_providers_registry = ProvidersRegistry()
921
 
 
 
657
        import errno
 
658
        if (isinstance(e, IOError) 
 
659
            and hasattr(e, 'errno')
 
660
            and e.errno == errno.EPIPE):
 
661
            bzrlib.trace.note('broken pipe')
 
662
            return 3
 
663
        else:
 
664
            bzrlib.trace.log_exception()
 
665
            if os.environ.get('BZR_PDB'):
 
666
                print '**** entering debugger'
 
667
                import pdb
 
668
                pdb.post_mortem(sys.exc_traceback)
 
669
            return 3
922
670
 
923
671
if __name__ == '__main__':
924
672
    sys.exit(main(sys.argv))