~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2006-03-03 08:55:34 UTC
  • mto: This revision was merged to the branch mainline in revision 1593.
  • Revision ID: mbp@sourcefrog.net-20060303085534-d24a8118f4ce571a
Add some tests that format7 repo creates the right lock type

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2004, 2005 by Canonical Ltd
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
#
 
12
 
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
18
# TODO: probably should say which arguments are candidates for glob
19
19
# expansion on windows and do that at the command level.
20
20
 
 
21
# TODO: Help messages for options.
 
22
 
21
23
# TODO: Define arguments by objects, rather than just using names.
22
24
# 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.
 
25
# would help with validation and shell completion.
27
26
 
28
27
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
29
28
# the profile output behind so it can be interactively examined?
30
29
 
 
30
import sys
31
31
import os
32
 
import sys
33
 
 
34
 
from bzrlib.lazy_import import lazy_import
35
 
lazy_import(globals(), """
36
 
import codecs
 
32
from warnings import warn
 
33
from inspect import getdoc
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
import bzrlib.trace
 
38
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
 
39
from bzrlib.errors import (BzrError, 
 
40
                           BzrCheckError,
 
41
                           BzrCommandError,
 
42
                           BzrOptionError,
 
43
                           NotBranchError)
 
44
from bzrlib.revisionspec import RevisionSpec
53
45
from bzrlib.option import Option
54
46
 
55
 
 
56
47
plugin_cmds = {}
57
48
 
58
49
 
59
50
def register_command(cmd, decorate=False):
60
 
    """Utility function to help register a command
61
 
 
62
 
    :param cmd: Command subclass to register
63
 
    :param decorate: If true, allow overriding an existing command
64
 
        of the same name; the old command is returned by this function.
65
 
        Otherwise it is an error to try to override an existing command.
66
 
    """
 
51
    "Utility function to help register a command"
67
52
    global plugin_cmds
68
53
    k = cmd.__name__
69
54
    if k.startswith("cmd_"):
70
55
        k_unsquished = _unsquish_command_name(k)
71
56
    else:
72
57
        k_unsquished = k
73
 
    if k_unsquished not in plugin_cmds:
 
58
    if not plugin_cmds.has_key(k_unsquished):
74
59
        plugin_cmds[k_unsquished] = cmd
75
 
        ## trace.mutter('registered plugin command %s', k_unsquished)
 
60
        mutter('registered plugin command %s', k_unsquished)      
76
61
        if decorate and k_unsquished in builtin_command_names():
77
62
            return _builtin_commands()[k_unsquished]
78
63
    elif decorate:
80
65
        plugin_cmds[k_unsquished] = cmd
81
66
        return result
82
67
    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__])
 
68
        log_error('Two plugins defined the same command: %r' % k)
 
69
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
87
70
 
88
71
 
89
72
def _squish_command_name(cmd):
91
74
 
92
75
 
93
76
def _unsquish_command_name(cmd):
 
77
    assert cmd.startswith("cmd_")
94
78
    return cmd[4:].replace('_','-')
95
79
 
96
80
 
100
84
    builtins = bzrlib.builtins.__dict__
101
85
    for name in builtins:
102
86
        if name.startswith("cmd_"):
103
 
            real_name = _unsquish_command_name(name)
 
87
            real_name = _unsquish_command_name(name)        
104
88
            r[real_name] = builtins[name]
105
89
    return r
 
90
 
106
91
            
107
92
 
108
93
def builtin_command_names():
134
119
    plugins_override
135
120
        If true, plugin commands can override builtins.
136
121
    """
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
122
    from bzrlib.externalcommand import ExternalCommand
146
123
 
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.
 
124
    cmd_name = str(cmd_name)            # not unicode
151
125
 
152
126
    # first look up this command under the specified name
153
127
    cmds = _get_cmd_dict(plugins_override=plugins_override)
165
139
    if cmd_obj:
166
140
        return cmd_obj
167
141
 
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
 
142
    raise BzrCommandError("unknown command %r" % cmd_name)
179
143
 
180
144
 
181
145
class Command(object):
219
183
    hidden
220
184
        If true, this command isn't advertised.  This is typically
221
185
        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
186
    """
239
187
    aliases = []
240
188
    takes_args = []
241
189
    takes_options = []
242
 
    encoding_type = 'strict'
243
190
 
244
191
    hidden = False
245
192
    
247
194
        """Construct an instance of this command."""
248
195
        if self.__doc__ == Command.__doc__:
249
196
            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
197
 
425
198
    def options(self):
426
199
        """Return dict of valid options for this command.
427
200
 
428
201
        Maps from long option name to option object."""
429
 
        r = Option.STD_OPTIONS.copy()
430
 
        std_names = r.keys()
 
202
        r = dict()
 
203
        r['help'] = Option.OPTIONS['help']
431
204
        for o in self.takes_options:
432
 
            if isinstance(o, basestring):
433
 
                o = option.Option.OPTIONS[o]
 
205
            if not isinstance(o, Option):
 
206
                o = Option.OPTIONS[o]
434
207
            r[o.name] = o
435
 
            if o.name in std_names:
436
 
                self.supported_std_options.append(o.name)
437
208
        return r
438
209
 
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
461
 
 
462
 
    def run_argv_aliases(self, argv, alias_argv=None):
463
 
        """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
 
        args, opts = parse_args(self, argv, alias_argv)
469
 
 
470
 
        # Process the standard options
 
210
    def run_argv(self, argv):
 
211
        """Parse command line and run."""
 
212
        args, opts = parse_args(self, argv)
471
213
        if 'help' in opts:  # e.g. bzr add --help
472
 
            sys.stdout.write(self.get_help_text())
 
214
            from bzrlib.help import help_on_command
 
215
            help_on_command(self.name())
473
216
            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
 
 
 
217
        # XXX: This should be handled by the parser
 
218
        allowed_names = self.options().keys()
 
219
        for oname in opts:
 
220
            if oname not in allowed_names:
 
221
                raise BzrCommandError("option '--%s' is not allowed for command %r"
 
222
                                      % (oname, self.name()))
484
223
        # mix arguments and options into one dictionary
485
224
        cmdargs = _match_argform(self.name(), self.takes_args, args)
486
225
        cmdopts = {}
490
229
        all_cmd_args = cmdargs.copy()
491
230
        all_cmd_args.update(cmdopts)
492
231
 
493
 
        self._setup_outf()
494
 
 
495
232
        return self.run(**all_cmd_args)
496
 
 
 
233
    
497
234
    def run(self):
498
235
        """Actually run the command.
499
236
 
504
241
        shell error code if not.  It's OK for this method to allow
505
242
        an exception to raise up.
506
243
        """
507
 
        raise NotImplementedError('no implementation of command %r'
508
 
                                  % self.name())
 
244
        raise NotImplementedError()
 
245
 
509
246
 
510
247
    def help(self):
511
248
        """Return help message for this class."""
512
 
        from inspect import getdoc
513
249
        if self.__doc__ is Command.__doc__:
514
250
            return None
515
251
        return getdoc(self)
517
253
    def name(self):
518
254
        return _unsquish_command_name(self.__class__.__name__)
519
255
 
520
 
    def plugin_name(self):
521
 
        """Get the name of the plugin that provides this command.
522
256
 
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]
 
257
def parse_spec(spec):
 
258
    """
 
259
    >>> parse_spec(None)
 
260
    [None, None]
 
261
    >>> parse_spec("./")
 
262
    ['./', None]
 
263
    >>> parse_spec("../@")
 
264
    ['..', -1]
 
265
    >>> parse_spec("../f/@35")
 
266
    ['../f', 35]
 
267
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
268
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
 
269
    """
 
270
    if spec is None:
 
271
        return [None, None]
 
272
    if '/@' in spec:
 
273
        parsed = spec.split('/@')
 
274
        assert len(parsed) == 2
 
275
        if parsed[1] == "":
 
276
            parsed[1] = -1
528
277
        else:
529
 
            return None
530
 
 
531
 
 
532
 
def parse_args(command, argv, alias_argv=None):
 
278
            try:
 
279
                parsed[1] = int(parsed[1])
 
280
            except ValueError:
 
281
                pass # We can allow stuff like ./@revid:blahblahblah
 
282
            else:
 
283
                assert parsed[1] >=0
 
284
    else:
 
285
        parsed = [spec, None]
 
286
    return parsed
 
287
 
 
288
def parse_args(command, argv):
533
289
    """Parse command line.
534
290
    
535
291
    Arguments and options are parsed at this level before being passed
537
293
    lookup table, something about the available options, what optargs
538
294
    they take, and which commands will accept them.
539
295
    """
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])
 
296
    # TODO: chop up this beast; make it a method of the Command
 
297
    args = []
 
298
    opts = {}
 
299
 
 
300
    cmd_options = command.options()
 
301
    argsover = False
 
302
    while argv:
 
303
        a = argv.pop(0)
 
304
        if argsover:
 
305
            args.append(a)
 
306
            continue
 
307
        elif a == '--':
 
308
            # We've received a standalone -- No more flags
 
309
            argsover = True
 
310
            continue
 
311
        if a[0] == '-':
 
312
            # option names must not be unicode
 
313
            a = str(a)
 
314
            optarg = None
 
315
            if a[1] == '-':
 
316
                mutter("  got option %r", a)
 
317
                if '=' in a:
 
318
                    optname, optarg = a[2:].split('=', 1)
 
319
                else:
 
320
                    optname = a[2:]
 
321
                if optname not in cmd_options:
 
322
                    raise BzrOptionError('unknown long option %r for command %s'
 
323
                        % (a, command.name()))
 
324
            else:
 
325
                shortopt = a[1:]
 
326
                if shortopt in Option.SHORT_OPTIONS:
 
327
                    # Multi-character options must have a space to delimit
 
328
                    # their value
 
329
                    # ^^^ what does this mean? mbp 20051014
 
330
                    optname = Option.SHORT_OPTIONS[shortopt].name
 
331
                else:
 
332
                    # Single character short options, can be chained,
 
333
                    # and have their value appended to their name
 
334
                    shortopt = a[1:2]
 
335
                    if shortopt not in Option.SHORT_OPTIONS:
 
336
                        # We didn't find the multi-character name, and we
 
337
                        # didn't find the single char name
 
338
                        raise BzrError('unknown short option %r' % a)
 
339
                    optname = Option.SHORT_OPTIONS[shortopt].name
 
340
 
 
341
                    if a[2:]:
 
342
                        # There are extra things on this option
 
343
                        # see if it is the value, or if it is another
 
344
                        # short option
 
345
                        optargfn = Option.OPTIONS[optname].type
 
346
                        if optargfn is None:
 
347
                            # This option does not take an argument, so the
 
348
                            # next entry is another short option, pack it back
 
349
                            # into the list
 
350
                            argv.insert(0, '-' + a[2:])
 
351
                        else:
 
352
                            # This option takes an argument, so pack it
 
353
                            # into the array
 
354
                            optarg = a[2:]
 
355
            
 
356
                if optname not in cmd_options:
 
357
                    raise BzrOptionError('unknown short option %r for command'
 
358
                        ' %s' % (shortopt, command.name()))
 
359
            if optname in opts:
 
360
                # XXX: Do we ever want to support this, e.g. for -r?
 
361
                raise BzrError('repeated option %r' % a)
 
362
                
 
363
            option_obj = cmd_options[optname]
 
364
            optargfn = option_obj.type
 
365
            if optargfn:
 
366
                if optarg == None:
 
367
                    if not argv:
 
368
                        raise BzrError('option %r needs an argument' % a)
 
369
                    else:
 
370
                        optarg = argv.pop(0)
 
371
                opts[optname] = optargfn(optarg)
 
372
            else:
 
373
                if optarg != None:
 
374
                    raise BzrError('option %r takes no argument' % optname)
 
375
                opts[optname] = True
 
376
        else:
 
377
            args.append(a)
550
378
    return args, opts
551
379
 
552
380
 
567
395
                argdict[argname + '_list'] = None
568
396
        elif ap[-1] == '+':
569
397
            if not args:
570
 
                raise errors.BzrCommandError("command %r needs one or more %s"
571
 
                                             % (cmd, argname.upper()))
 
398
                raise BzrCommandError("command %r needs one or more %s"
 
399
                        % (cmd, argname.upper()))
572
400
            else:
573
401
                argdict[argname + '_list'] = args[:]
574
402
                args = []
575
403
        elif ap[-1] == '$': # all but one
576
404
            if len(args) < 2:
577
 
                raise errors.BzrCommandError("command %r needs one or more %s"
578
 
                                             % (cmd, argname.upper()))
 
405
                raise BzrCommandError("command %r needs one or more %s"
 
406
                        % (cmd, argname.upper()))
579
407
            argdict[argname + '_list'] = args[:-1]
580
 
            args[:-1] = []
 
408
            args[:-1] = []                
581
409
        else:
582
410
            # just a plain arg
583
411
            argname = ap
584
412
            if not args:
585
 
                raise errors.BzrCommandError("command %r requires argument %s"
586
 
                               % (cmd, argname.upper()))
 
413
                raise BzrCommandError("command %r requires argument %s"
 
414
                        % (cmd, argname.upper()))
587
415
            else:
588
416
                argdict[argname] = args.pop(0)
589
417
            
590
418
    if args:
591
 
        raise errors.BzrCommandError("extra argument to command %s: %s"
592
 
                                     % (cmd, args[0]))
 
419
        raise BzrCommandError("extra argument to command %s: %s"
 
420
                              % (cmd, args[0]))
593
421
 
594
422
    return argdict
595
423
 
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
424
 
611
425
 
612
426
def apply_profiled(the_callable, *args, **kwargs):
634
448
 
635
449
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
636
450
    from bzrlib.lsprof import profile
 
451
    import cPickle
637
452
    ret, stats = profile(the_callable, *args, **kwargs)
638
453
    stats.sort()
639
454
    if filename is None:
640
455
        stats.pprint()
641
456
    else:
642
 
        stats.save(filename)
643
 
        trace.note('Profile data written to "%s".', filename)
 
457
        stats.freeze()
 
458
        cPickle.dump(stats, open(filename, 'w'), 2)
 
459
        print 'Profile data written to %r.' % filename
644
460
    return ret
645
461
 
646
 
 
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)
666
 
    if (alias):
667
 
        return shlex_split_unicode(alias)
668
 
    return None
669
 
 
670
 
 
671
462
def run_bzr(argv):
672
463
    """Execute a command.
673
464
 
 
465
    This is similar to main(), but without all the trappings for
 
466
    logging and error handling.  
 
467
    
674
468
    argv
675
469
       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
470
    
679
471
    Returns a command status or raises an exception.
680
472
 
684
476
    --no-plugins
685
477
        Do not load plugin modules at all
686
478
 
687
 
    --no-aliases
688
 
        Do not allow aliases
689
 
 
690
479
    --builtin
691
480
        Only use builtin commands.  (Plugins are still allowed to change
692
481
        other behaviour.)
696
485
 
697
486
    --lsprof
698
487
        Run under the Python lsprof profiler.
699
 
 
700
 
    --coverage
701
 
        Generate line coverage report in the specified directory.
702
488
    """
703
 
    argv = list(argv)
704
 
    trace.mutter("bzr arguments: %r", argv)
 
489
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
705
490
 
706
 
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
707
 
                opt_no_aliases = False
708
 
    opt_lsprof_file = opt_coverage_dir = None
 
491
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin = False
 
492
    opt_lsprof_file = None
709
493
 
710
494
    # --no-plugins is handled specially at a very early stage. We need
711
495
    # to load plugins before doing other command parsing so that they
720
504
        elif a == '--lsprof':
721
505
            opt_lsprof = True
722
506
        elif a == '--lsprof-file':
723
 
            opt_lsprof = True
724
507
            opt_lsprof_file = argv[i + 1]
725
508
            i += 1
726
509
        elif a == '--no-plugins':
727
510
            opt_no_plugins = True
728
 
        elif a == '--no-aliases':
729
 
            opt_no_aliases = True
730
511
        elif a == '--builtin':
731
512
            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:])
 
513
        elif a in ('--quiet', '-q'):
 
514
            be_quiet()
737
515
        else:
738
516
            argv_copy.append(a)
739
517
        i += 1
740
518
 
741
519
    argv = argv_copy
742
 
    if (not argv):
743
 
        from bzrlib.builtins import cmd_help
744
 
        cmd_help().run_argv_aliases([])
 
520
    if (not argv) or (argv[0] == '--help'):
 
521
        from bzrlib.help import help
 
522
        if len(argv) > 1:
 
523
            help(argv[1])
 
524
        else:
 
525
            help()
745
526
        return 0
746
527
 
747
528
    if argv[0] == '--version':
748
 
        from bzrlib.builtins import cmd_version
749
 
        cmd_version().run_argv_aliases([])
 
529
        from bzrlib.builtins import show_version
 
530
        show_version()
750
531
        return 0
751
 
 
 
532
        
752
533
    if not opt_no_plugins:
753
534
        from bzrlib.plugin import load_plugins
754
535
        load_plugins()
756
537
        from bzrlib.plugin import disable_plugins
757
538
        disable_plugins()
758
539
 
759
 
    alias_argv = None
760
 
 
761
 
    if not opt_no_aliases:
762
 
        alias_argv = get_alias(argv[0])
763
 
        if alias_argv:
764
 
            user_encoding = osutils.get_user_encoding()
765
 
            alias_argv = [a.decode(user_encoding) for a in alias_argv]
766
 
            argv[0] = alias_argv.pop(0)
767
 
 
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.
 
540
    cmd = str(argv.pop(0))
772
541
 
773
542
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
774
 
    run = cmd_obj.run_argv_aliases
775
 
    run_argv = [argv, alias_argv]
776
543
 
777
544
    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
545
        if opt_lsprof:
783
 
            if opt_coverage_dir:
784
 
                trace.warning(
785
 
                    '--coverage ignored, because --lsprof is in use.')
786
 
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
 
546
            ret = apply_lsprofiled(opt_lsprof_file, cmd_obj.run_argv, argv)
787
547
        elif opt_profile:
788
 
            if opt_coverage_dir:
789
 
                trace.warning(
790
 
                    '--coverage ignored, because --profile is in use.')
791
 
            ret = apply_profiled(run, *run_argv)
792
 
        elif opt_coverage_dir:
793
 
            ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
 
548
            ret = apply_profiled(cmd_obj.run_argv, argv)
794
549
        else:
795
 
            ret = run(*run_argv)
796
 
        if 'memory' in debug.debug_flags:
797
 
            trace.debug_memory('Process status after command:', short=False)
 
550
            ret = cmd_obj.run_argv(argv)
798
551
        return ret or 0
799
552
    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
 
553
        # reset, in case we may do other commands later within the same process
 
554
        be_quiet(False)
804
555
 
805
556
def display_command(func):
806
557
    """Decorator that suppresses pipe/interrupt errors."""
810
561
            sys.stdout.flush()
811
562
            return result
812
563
        except IOError, e:
813
 
            if getattr(e, 'errno', None) is None:
 
564
            if not hasattr(e, 'errno'):
814
565
                raise
815
566
            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
 
567
                raise
819
568
            pass
820
569
        except KeyboardInterrupt:
821
570
            pass
825
574
def main(argv):
826
575
    import bzrlib.ui
827
576
    from bzrlib.ui.text import TextUIFactory
 
577
    ## bzrlib.trace.enable_default_logging()
 
578
    bzrlib.trace.log_startup(argv)
828
579
    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)
 
580
    ret = run_bzr_catch_errors(argv[1:])
 
581
    mutter("return code %d", ret)
842
582
    return ret
843
583
 
844
584
 
845
585
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
586
    try:
849
 
        return run_bzr(argv)
850
 
    except (KeyboardInterrupt, Exception), e:
 
587
        try:
 
588
            return run_bzr(argv)
 
589
        finally:
 
590
            # do this here inside the exception wrappers to catch EPIPE
 
591
            sys.stdout.flush()
 
592
    except Exception, e:
851
593
        # used to handle AssertionError and KeyboardInterrupt
852
594
        # 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
 
 
 
595
        import errno
 
596
        if (isinstance(e, IOError) 
 
597
            and hasattr(e, 'errno')
 
598
            and e.errno == errno.EPIPE):
 
599
            bzrlib.trace.note('broken pipe')
 
600
            return 3
 
601
        else:
 
602
            bzrlib.trace.log_exception()
 
603
            if os.environ.get('BZR_PDB'):
 
604
                print '**** entering debugger'
 
605
                import pdb
 
606
                pdb.post_mortem(sys.exc_traceback)
 
607
            return 3
922
608
 
923
609
if __name__ == '__main__':
924
610
    sys.exit(main(sys.argv))