~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-04-17 08:04:15 UTC
  • mfrom: (2423.1.2 benchmarks)
  • Revision ID: pqm@pqm.ubuntu.com-20070417080415-5vn25svmf95ki88z
Also clear SmartTCPServer hooks from TestCase._clear_hooks

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 by Canonical Ltd
 
1
# Copyright (C) 2006 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 os
31
32
import sys
32
 
import os
 
33
 
 
34
from bzrlib.lazy_import import lazy_import
 
35
lazy_import(globals(), """
 
36
import codecs
 
37
import errno
33
38
from warnings import warn
34
 
import errno
35
 
import codecs
36
39
 
37
40
import bzrlib
38
 
import bzrlib.errors as errors
39
 
from bzrlib.errors import (BzrError,
40
 
                           BzrCommandError,
41
 
                           BzrCheckError,
42
 
                           NotBranchError)
 
41
from bzrlib import (
 
42
    debug,
 
43
    errors,
 
44
    option,
 
45
    osutils,
 
46
    trace,
 
47
    )
 
48
""")
 
49
 
 
50
from bzrlib.symbol_versioning import (
 
51
    deprecated_function,
 
52
    deprecated_method,
 
53
    zero_eight,
 
54
    zero_eleven,
 
55
    )
 
56
# Compatibility
43
57
from bzrlib.option import Option
44
 
import bzrlib.osutils
45
 
from bzrlib.revisionspec import RevisionSpec
46
 
from bzrlib.symbol_versioning import (deprecated_method, zero_eight)
47
 
import bzrlib.trace
48
 
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
 
58
 
49
59
 
50
60
plugin_cmds = {}
51
61
 
64
74
        k_unsquished = _unsquish_command_name(k)
65
75
    else:
66
76
        k_unsquished = k
67
 
    if not plugin_cmds.has_key(k_unsquished):
 
77
    if k_unsquished not in plugin_cmds:
68
78
        plugin_cmds[k_unsquished] = cmd
69
 
        mutter('registered plugin command %s', k_unsquished)
 
79
        ## trace.mutter('registered plugin command %s', k_unsquished)
70
80
        if decorate and k_unsquished in builtin_command_names():
71
81
            return _builtin_commands()[k_unsquished]
72
82
    elif decorate:
74
84
        plugin_cmds[k_unsquished] = cmd
75
85
        return result
76
86
    else:
77
 
        log_error('Two plugins defined the same command: %r' % k)
78
 
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
87
        trace.log_error('Two plugins defined the same command: %r' % k)
 
88
        trace.log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
79
89
 
80
90
 
81
91
def _squish_command_name(cmd):
129
139
    """
130
140
    from bzrlib.externalcommand import ExternalCommand
131
141
 
132
 
    cmd_name = str(cmd_name)            # not unicode
 
142
    # We want only 'ascii' command names, but the user may have typed
 
143
    # in a Unicode name. In that case, they should just get a
 
144
    # 'command not found' error later.
 
145
    # In the future, we may actually support Unicode command names.
133
146
 
134
147
    # first look up this command under the specified name
135
148
    cmds = _get_cmd_dict(plugins_override=plugins_override)
147
160
    if cmd_obj:
148
161
        return cmd_obj
149
162
 
150
 
    raise BzrCommandError('unknown command "%s"' % cmd_name)
 
163
    raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
151
164
 
152
165
 
153
166
class Command(object):
201
214
            replace - put in a bogus character (typically '?')
202
215
            exact - do not encode sys.stdout
203
216
 
 
217
            NOTE: by default on Windows, sys.stdout is opened as a text
 
218
            stream, therefore LF line-endings are converted to CRLF.
 
219
            When a command uses encoding_type = 'exact', then
 
220
            sys.stdout is forced to be a binary stream, and line-endings
 
221
            will not mangled.
 
222
 
204
223
    """
205
224
    aliases = []
206
225
    takes_args = []
219
238
 
220
239
        Maps from long option name to option object."""
221
240
        r = dict()
222
 
        r['help'] = Option.OPTIONS['help']
 
241
        r['help'] = option.Option.OPTIONS['help']
223
242
        for o in self.takes_options:
224
 
            if not isinstance(o, Option):
225
 
                o = Option.OPTIONS[o]
 
243
            if isinstance(o, basestring):
 
244
                o = option.Option.OPTIONS[o]
226
245
            r[o.name] = o
227
246
        return r
228
247
 
233
252
        # Originally I was using self.stdout, but that looks
234
253
        # *way* too much like sys.stdout
235
254
        if self.encoding_type == 'exact':
 
255
            # force sys.stdout to be binary stream on win32
 
256
            if sys.platform == 'win32':
 
257
                fileno = getattr(sys.stdout, 'fileno', None)
 
258
                if fileno:
 
259
                    import msvcrt
 
260
                    msvcrt.setmode(fileno(), os.O_BINARY)
236
261
            self.outf = sys.stdout
237
262
            return
238
263
 
239
 
        output_encoding = bzrlib.osutils.get_terminal_encoding()
 
264
        output_encoding = osutils.get_terminal_encoding()
240
265
 
241
266
        # use 'replace' so that we don't abort if trying to write out
242
267
        # in e.g. the default C locale.
246
271
        # bogus. So set the attribute, so we can find the correct encoding later.
247
272
        self.outf.encoding = output_encoding
248
273
 
249
 
    @deprecated_method(zero_eight)
250
 
    def run_argv(self, argv):
251
 
        """Parse command line and run.
252
 
        
253
 
        See run_argv_aliases for the 0.8 and beyond api.
254
 
        """
255
 
        return self.run_argv_aliases(argv)
256
 
 
257
274
    def run_argv_aliases(self, argv, alias_argv=None):
258
275
        """Parse the command line and run with extra aliases in alias_argv."""
 
276
        if argv is None:
 
277
            warn("Passing None for [] is deprecated from bzrlib 0.10",
 
278
                 DeprecationWarning, stacklevel=2)
 
279
            argv = []
259
280
        args, opts = parse_args(self, argv, alias_argv)
260
281
        if 'help' in opts:  # e.g. bzr add --help
261
282
            from bzrlib.help import help_on_command
262
283
            help_on_command(self.name())
263
284
            return 0
264
 
        # XXX: This should be handled by the parser
265
 
        allowed_names = self.options().keys()
266
 
        for oname in opts:
267
 
            if oname not in allowed_names:
268
 
                raise BzrOptionError("option '--%s' is not allowed for"
269
 
                                " command %r" % (oname, self.name()))
270
285
        # mix arguments and options into one dictionary
271
286
        cmdargs = _match_argform(self.name(), self.takes_args, args)
272
287
        cmdopts = {}
290
305
        shell error code if not.  It's OK for this method to allow
291
306
        an exception to raise up.
292
307
        """
293
 
        raise NotImplementedError('no implementation of command %r' 
 
308
        raise NotImplementedError('no implementation of command %r'
294
309
                                  % self.name())
295
310
 
296
311
    def help(self):
315
330
            return None
316
331
 
317
332
 
 
333
# Technically, this function hasn't been use in a *really* long time
 
334
# but we are only deprecating it now.
 
335
@deprecated_function(zero_eleven)
318
336
def parse_spec(spec):
319
337
    """
320
338
    >>> parse_spec(None)
354
372
    lookup table, something about the available options, what optargs
355
373
    they take, and which commands will accept them.
356
374
    """
357
 
    # TODO: chop up this beast; make it a method of the Command
358
 
    args = []
359
 
    opts = {}
360
 
    alias_opts = {}
361
 
 
362
 
    cmd_options = command.options()
363
 
    argsover = False
364
 
    proc_aliasarg = True # Are we processing alias_argv now?
365
 
    for proc_argv in alias_argv, argv:
366
 
        while proc_argv:
367
 
            a = proc_argv.pop(0)
368
 
            if argsover:
369
 
                args.append(a)
370
 
                continue
371
 
            elif a == '-':
372
 
                args.append(a)
373
 
                continue
374
 
            elif a == '--':
375
 
                # We've received a standalone -- No more flags
376
 
                argsover = True
377
 
                continue
378
 
            if a[0] == '-':
379
 
                # option names must not be unicode
380
 
                a = str(a)
381
 
                optarg = None
382
 
                if a[1] == '-':
383
 
                    mutter("  got option %r", a)
384
 
                    if '=' in a:
385
 
                        optname, optarg = a[2:].split('=', 1)
386
 
                    else:
387
 
                        optname = a[2:]
388
 
                    if optname not in cmd_options:
389
 
                        raise BzrCommandError('unknown option "%s"' % a)
390
 
                else:
391
 
                    shortopt = a[1:]
392
 
                    if shortopt in Option.SHORT_OPTIONS:
393
 
                        # Multi-character options must have a space to delimit
394
 
                        # their value
395
 
                        # ^^^ what does this mean? mbp 20051014
396
 
                        optname = Option.SHORT_OPTIONS[shortopt].name
397
 
                    else:
398
 
                        # Single character short options, can be chained,
399
 
                        # and have their value appended to their name
400
 
                        shortopt = a[1:2]
401
 
                        if shortopt not in Option.SHORT_OPTIONS:
402
 
                            # We didn't find the multi-character name, and we
403
 
                            # didn't find the single char name
404
 
                            raise BzrCommandError('unknown option "%s"' % a)
405
 
                        optname = Option.SHORT_OPTIONS[shortopt].name
406
 
 
407
 
                        if a[2:]:
408
 
                            # There are extra things on this option
409
 
                            # see if it is the value, or if it is another
410
 
                            # short option
411
 
                            optargfn = Option.OPTIONS[optname].type
412
 
                            if optargfn is None:
413
 
                                # This option does not take an argument, so the
414
 
                                # next entry is another short option, pack it
415
 
                                # back into the list
416
 
                                proc_argv.insert(0, '-' + a[2:])
417
 
                            else:
418
 
                                # This option takes an argument, so pack it
419
 
                                # into the array
420
 
                                optarg = a[2:]
421
 
                    if optname not in cmd_options:
422
 
                        raise BzrCommandError('unknown option "%s"' % shortopt)
423
 
                if optname in opts:
424
 
                    # XXX: Do we ever want to support this, e.g. for -r?
425
 
                    if proc_aliasarg:
426
 
                        raise BzrCommandError('repeated option %r' % a)
427
 
                    elif optname in alias_opts:
428
 
                        # Replace what's in the alias with what's in the real
429
 
                        # argument
430
 
                        del alias_opts[optname]
431
 
                        del opts[optname]
432
 
                        proc_argv.insert(0, a)
433
 
                        continue
434
 
                    else:
435
 
                        raise BzrCommandError('repeated option %r' % a)
436
 
                    
437
 
                option_obj = cmd_options[optname]
438
 
                optargfn = option_obj.type
439
 
                if optargfn:
440
 
                    if optarg == None:
441
 
                        if not proc_argv:
442
 
                            raise BzrCommandError('option %r needs an argument' % a)
443
 
                        else:
444
 
                            optarg = proc_argv.pop(0)
445
 
                    opts[optname] = optargfn(optarg)
446
 
                    if proc_aliasarg:
447
 
                        alias_opts[optname] = optargfn(optarg)
448
 
                else:
449
 
                    if optarg != None:
450
 
                        raise BzrCommandError('option %r takes no argument' % optname)
451
 
                    opts[optname] = True
452
 
                    if proc_aliasarg:
453
 
                        alias_opts[optname] = True
454
 
            else:
455
 
                args.append(a)
456
 
        proc_aliasarg = False # Done with alias argv
 
375
    # TODO: make it a method of the Command?
 
376
    parser = option.get_optparser(command.options())
 
377
    if alias_argv is not None:
 
378
        args = alias_argv + argv
 
379
    else:
 
380
        args = argv
 
381
 
 
382
    options, args = parser.parse_args(args)
 
383
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
 
384
                 v is not option.OptionParser.DEFAULT_VALUE])
457
385
    return args, opts
458
386
 
459
387
 
474
402
                argdict[argname + '_list'] = None
475
403
        elif ap[-1] == '+':
476
404
            if not args:
477
 
                raise BzrCommandError("command %r needs one or more %s"
478
 
                        % (cmd, argname.upper()))
 
405
                raise errors.BzrCommandError("command %r needs one or more %s"
 
406
                                             % (cmd, argname.upper()))
479
407
            else:
480
408
                argdict[argname + '_list'] = args[:]
481
409
                args = []
482
410
        elif ap[-1] == '$': # all but one
483
411
            if len(args) < 2:
484
 
                raise BzrCommandError("command %r needs one or more %s"
485
 
                        % (cmd, argname.upper()))
 
412
                raise errors.BzrCommandError("command %r needs one or more %s"
 
413
                                             % (cmd, argname.upper()))
486
414
            argdict[argname + '_list'] = args[:-1]
487
415
            args[:-1] = []
488
416
        else:
489
417
            # just a plain arg
490
418
            argname = ap
491
419
            if not args:
492
 
                raise BzrCommandError("command %r requires argument %s"
493
 
                        % (cmd, argname.upper()))
 
420
                raise errors.BzrCommandError("command %r requires argument %s"
 
421
                               % (cmd, argname.upper()))
494
422
            else:
495
423
                argdict[argname] = args.pop(0)
496
424
            
497
425
    if args:
498
 
        raise BzrCommandError("extra argument to command %s: %s"
499
 
                              % (cmd, args[0]))
 
426
        raise errors.BzrCommandError("extra argument to command %s: %s"
 
427
                                     % (cmd, args[0]))
500
428
 
501
429
    return argdict
502
430
 
539
467
    return ret
540
468
 
541
469
 
542
 
def get_alias(cmd):
543
 
    """Return an expanded alias, or None if no alias exists"""
544
 
    import bzrlib.config
545
 
    alias = bzrlib.config.GlobalConfig().get_alias(cmd)
 
470
def get_alias(cmd, config=None):
 
471
    """Return an expanded alias, or None if no alias exists.
 
472
 
 
473
    cmd
 
474
        Command to be checked for an alias.
 
475
    config
 
476
        Used to specify an alternative config to use,
 
477
        which is especially useful for testing.
 
478
        If it is unspecified, the global config will be used.
 
479
    """
 
480
    if config is None:
 
481
        import bzrlib.config
 
482
        config = bzrlib.config.GlobalConfig()
 
483
    alias = config.get_alias(cmd)
546
484
    if (alias):
547
 
        return alias.split(' ')
 
485
        import shlex
 
486
        return [a.decode('utf-8') for a in shlex.split(alias.encode('utf-8'))]
548
487
    return None
549
488
 
550
489
 
581
520
        Run under the Python lsprof profiler.
582
521
    """
583
522
    argv = list(argv)
 
523
    trace.mutter("bzr arguments: %r", argv)
584
524
 
585
525
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
586
526
                opt_no_aliases = False
609
549
        elif a == '--builtin':
610
550
            opt_builtin = True
611
551
        elif a in ('--quiet', '-q'):
612
 
            be_quiet()
 
552
            trace.be_quiet()
 
553
        elif a.startswith('-D'):
 
554
            debug.debug_flags.add(a[2:])
613
555
        else:
614
556
            argv_copy.append(a)
615
557
        i += 1
621
563
        return 0
622
564
 
623
565
    if argv[0] == '--version':
624
 
        from bzrlib.builtins import show_version
 
566
        from bzrlib.version import show_version
625
567
        show_version()
626
568
        return 0
627
569
        
640
582
            alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
641
583
            argv[0] = alias_argv.pop(0)
642
584
 
643
 
    cmd = str(argv.pop(0))
 
585
    cmd = argv.pop(0)
 
586
    # We want only 'ascii' command names, but the user may have typed
 
587
    # in a Unicode name. In that case, they should just get a
 
588
    # 'command not found' error later.
644
589
 
645
590
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
646
 
    if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
647
 
        run = cmd_obj.run_argv
648
 
        run_argv = [argv]
649
 
    else:
650
 
        run = cmd_obj.run_argv_aliases
651
 
        run_argv = [argv, alias_argv]
 
591
    run = cmd_obj.run_argv_aliases
 
592
    run_argv = [argv, alias_argv]
652
593
 
653
594
    try:
654
595
        if opt_lsprof:
660
601
        return ret or 0
661
602
    finally:
662
603
        # reset, in case we may do other commands later within the same process
663
 
        be_quiet(False)
 
604
        trace.be_quiet(False)
664
605
 
665
606
def display_command(func):
666
607
    """Decorator that suppresses pipe/interrupt errors."""
670
611
            sys.stdout.flush()
671
612
            return result
672
613
        except IOError, e:
673
 
            if not hasattr(e, 'errno'):
 
614
            if getattr(e, 'errno', None) is None:
674
615
                raise
675
616
            if e.errno != errno.EPIPE:
676
617
                # Win32 raises IOError with errno=0 on a broken pipe
677
 
                if sys.platform != 'win32' or e.errno != 0:
 
618
                if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
678
619
                    raise
679
620
            pass
680
621
        except KeyboardInterrupt:
688
629
    bzrlib.ui.ui_factory = TextUIFactory()
689
630
    argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
690
631
    ret = run_bzr_catch_errors(argv)
691
 
    mutter("return code %d", ret)
 
632
    trace.mutter("return code %d", ret)
692
633
    return ret
693
634
 
694
635
 
697
638
        return run_bzr(argv)
698
639
        # do this here inside the exception wrappers to catch EPIPE
699
640
        sys.stdout.flush()
700
 
    except Exception, e:
 
641
    except (KeyboardInterrupt, Exception), e:
701
642
        # used to handle AssertionError and KeyboardInterrupt
702
643
        # specially here, but hopefully they're handled ok by the logger now
703
 
        bzrlib.trace.report_exception(sys.exc_info(), sys.stderr)
 
644
        trace.report_exception(sys.exc_info(), sys.stderr)
704
645
        if os.environ.get('BZR_PDB'):
705
646
            print '**** entering debugger'
706
647
            import pdb