~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Aaron Bentley
  • Date: 2006-09-21 17:40:20 UTC
  • mto: This revision was merged to the branch mainline in revision 2048.
  • Revision ID: abentley@panoramicfeedback.com-20060921174020-5a6a95957ad5dd7b
Implement testament format 3 strict

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 by Canonical Ltd
2
 
 
 
1
# Copyright (C) 2006 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
 
 
23
21
# TODO: Define arguments by objects, rather than just using names.
24
22
# Those objects can specify the expected type of the argument, which
25
 
# would help with validation and shell completion.
 
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.
26
27
 
27
28
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
28
29
# the profile output behind so it can be interactively examined?
29
30
 
30
 
import sys
 
31
import codecs
 
32
import errno
31
33
import os
32
34
from warnings import warn
33
 
from inspect import getdoc
 
35
import sys
34
36
 
35
37
import bzrlib
 
38
import bzrlib.errors as errors
 
39
from bzrlib.errors import (BzrError,
 
40
                           BzrCommandError,
 
41
                           BzrCheckError,
 
42
                           NotBranchError)
 
43
from bzrlib import option
 
44
from bzrlib.option import Option
 
45
import bzrlib.osutils
 
46
from bzrlib.symbol_versioning import (deprecated_method, zero_eight)
36
47
import bzrlib.trace
37
 
from bzrlib.trace import mutter, note, log_error, warning
38
 
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
39
 
from bzrlib.revisionspec import RevisionSpec
40
 
from bzrlib import BZRDIR
41
 
from bzrlib.option import Option
 
48
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
42
49
 
43
50
plugin_cmds = {}
44
51
 
45
52
 
46
 
def register_command(cmd):
47
 
    "Utility function to help register a command"
 
53
def register_command(cmd, decorate=False):
 
54
    """Utility function to help register a command
 
55
 
 
56
    :param cmd: Command subclass to register
 
57
    :param decorate: If true, allow overriding an existing command
 
58
        of the same name; the old command is returned by this function.
 
59
        Otherwise it is an error to try to override an existing command.
 
60
    """
48
61
    global plugin_cmds
49
62
    k = cmd.__name__
50
63
    if k.startswith("cmd_"):
51
64
        k_unsquished = _unsquish_command_name(k)
52
65
    else:
53
66
        k_unsquished = k
54
 
    if not plugin_cmds.has_key(k_unsquished):
55
 
        plugin_cmds[k_unsquished] = cmd
56
 
        mutter('registered plugin command %s', k_unsquished)      
 
67
    if k_unsquished not in plugin_cmds:
 
68
        plugin_cmds[k_unsquished] = cmd
 
69
        mutter('registered plugin command %s', k_unsquished)
 
70
        if decorate and k_unsquished in builtin_command_names():
 
71
            return _builtin_commands()[k_unsquished]
 
72
    elif decorate:
 
73
        result = plugin_cmds[k_unsquished]
 
74
        plugin_cmds[k_unsquished] = cmd
 
75
        return result
57
76
    else:
58
77
        log_error('Two plugins defined the same command: %r' % k)
59
78
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
74
93
    builtins = bzrlib.builtins.__dict__
75
94
    for name in builtins:
76
95
        if name.startswith("cmd_"):
77
 
            real_name = _unsquish_command_name(name)        
 
96
            real_name = _unsquish_command_name(name)
78
97
            r[real_name] = builtins[name]
79
98
    return r
80
 
 
81
99
            
82
100
 
83
101
def builtin_command_names():
111
129
    """
112
130
    from bzrlib.externalcommand import ExternalCommand
113
131
 
114
 
    cmd_name = str(cmd_name)            # not unicode
 
132
    # We want only 'ascii' command names, but the user may have typed
 
133
    # in a Unicode name. In that case, they should just get a
 
134
    # 'command not found' error later.
 
135
    # In the future, we may actually support Unicode command names.
115
136
 
116
137
    # first look up this command under the specified name
117
138
    cmds = _get_cmd_dict(plugins_override=plugins_override)
129
150
    if cmd_obj:
130
151
        return cmd_obj
131
152
 
132
 
    raise BzrCommandError("unknown command %r" % cmd_name)
 
153
    raise BzrCommandError('unknown command "%s"' % cmd_name)
133
154
 
134
155
 
135
156
class Command(object):
157
178
        List of argument forms, marked with whether they are optional,
158
179
        repeated, etc.
159
180
 
 
181
                Examples:
 
182
 
 
183
                ['to_location', 'from_branch?', 'file*']
 
184
 
 
185
                'to_location' is required
 
186
                'from_branch' is optional
 
187
                'file' can be specified 0 or more times
 
188
 
160
189
    takes_options
161
190
        List of options that may be given for this command.  These can
162
191
        be either strings, referring to globally-defined options,
165
194
    hidden
166
195
        If true, this command isn't advertised.  This is typically
167
196
        for commands intended for expert users.
 
197
 
 
198
    encoding_type
 
199
        Command objects will get a 'outf' attribute, which has been
 
200
        setup to properly handle encoding of unicode strings.
 
201
        encoding_type determines what will happen when characters cannot
 
202
        be encoded
 
203
            strict - abort if we cannot decode
 
204
            replace - put in a bogus character (typically '?')
 
205
            exact - do not encode sys.stdout
 
206
 
168
207
    """
169
208
    aliases = []
170
209
    takes_args = []
171
210
    takes_options = []
 
211
    encoding_type = 'strict'
172
212
 
173
213
    hidden = False
174
214
    
184
224
        r = dict()
185
225
        r['help'] = Option.OPTIONS['help']
186
226
        for o in self.takes_options:
187
 
            if not isinstance(o, Option):
 
227
            if isinstance(o, basestring):
188
228
                o = Option.OPTIONS[o]
189
229
            r[o.name] = o
190
230
        return r
191
231
 
 
232
    def _setup_outf(self):
 
233
        """Return a file linked to stdout, which has proper encoding."""
 
234
        assert self.encoding_type in ['strict', 'exact', 'replace']
 
235
 
 
236
        # Originally I was using self.stdout, but that looks
 
237
        # *way* too much like sys.stdout
 
238
        if self.encoding_type == 'exact':
 
239
            self.outf = sys.stdout
 
240
            return
 
241
 
 
242
        output_encoding = bzrlib.osutils.get_terminal_encoding()
 
243
 
 
244
        # use 'replace' so that we don't abort if trying to write out
 
245
        # in e.g. the default C locale.
 
246
        self.outf = codecs.getwriter(output_encoding)(sys.stdout, errors=self.encoding_type)
 
247
        # For whatever reason codecs.getwriter() does not advertise its encoding
 
248
        # it just returns the encoding of the wrapped file, which is completely
 
249
        # bogus. So set the attribute, so we can find the correct encoding later.
 
250
        self.outf.encoding = output_encoding
 
251
 
 
252
    @deprecated_method(zero_eight)
192
253
    def run_argv(self, argv):
193
 
        """Parse command line and run."""
194
 
        args, opts = parse_args(self, argv)
 
254
        """Parse command line and run.
 
255
        
 
256
        See run_argv_aliases for the 0.8 and beyond api.
 
257
        """
 
258
        return self.run_argv_aliases(argv)
 
259
 
 
260
    def run_argv_aliases(self, argv, alias_argv=None):
 
261
        """Parse the command line and run with extra aliases in alias_argv."""
 
262
        if argv is None:
 
263
            warn("Passing None for [] is deprecated from bzrlib 0.10", 
 
264
                 DeprecationWarning, stacklevel=2)
 
265
            argv = []
 
266
        args, opts = parse_args(self, argv, alias_argv)
195
267
        if 'help' in opts:  # e.g. bzr add --help
196
268
            from bzrlib.help import help_on_command
197
269
            help_on_command(self.name())
198
270
            return 0
199
 
        # XXX: This should be handled by the parser
200
 
        allowed_names = self.options().keys()
201
 
        for oname in opts:
202
 
            if oname not in allowed_names:
203
 
                raise BzrCommandError("option '--%s' is not allowed for command %r"
204
 
                                      % (oname, self.name()))
205
271
        # mix arguments and options into one dictionary
206
272
        cmdargs = _match_argform(self.name(), self.takes_args, args)
207
273
        cmdopts = {}
211
277
        all_cmd_args = cmdargs.copy()
212
278
        all_cmd_args.update(cmdopts)
213
279
 
 
280
        self._setup_outf()
 
281
 
214
282
        return self.run(**all_cmd_args)
215
 
 
216
283
    
217
284
    def run(self):
218
285
        """Actually run the command.
224
291
        shell error code if not.  It's OK for this method to allow
225
292
        an exception to raise up.
226
293
        """
227
 
        raise NotImplementedError()
228
 
 
 
294
        raise NotImplementedError('no implementation of command %r' 
 
295
                                  % self.name())
229
296
 
230
297
    def help(self):
231
298
        """Return help message for this class."""
 
299
        from inspect import getdoc
232
300
        if self.__doc__ is Command.__doc__:
233
301
            return None
234
302
        return getdoc(self)
236
304
    def name(self):
237
305
        return _unsquish_command_name(self.__class__.__name__)
238
306
 
 
307
    def plugin_name(self):
 
308
        """Get the name of the plugin that provides this command.
 
309
 
 
310
        :return: The name of the plugin or None if the command is builtin.
 
311
        """
 
312
        mod_parts = self.__module__.split('.')
 
313
        if len(mod_parts) >= 3 and mod_parts[1] == 'plugins':
 
314
            return mod_parts[2]
 
315
        else:
 
316
            return None
 
317
 
239
318
 
240
319
def parse_spec(spec):
241
320
    """
268
347
        parsed = [spec, None]
269
348
    return parsed
270
349
 
271
 
def parse_args(command, argv):
 
350
def parse_args(command, argv, alias_argv=None):
272
351
    """Parse command line.
273
352
    
274
353
    Arguments and options are parsed at this level before being passed
276
355
    lookup table, something about the available options, what optargs
277
356
    they take, and which commands will accept them.
278
357
    """
279
 
    # TODO: chop up this beast; make it a method of the Command
280
 
    args = []
281
 
    opts = {}
282
 
 
283
 
    cmd_options = command.options()
284
 
    argsover = False
285
 
    while argv:
286
 
        a = argv.pop(0)
287
 
        if argsover:
288
 
            args.append(a)
289
 
            continue
290
 
        elif a == '--':
291
 
            # We've received a standalone -- No more flags
292
 
            argsover = True
293
 
            continue
294
 
        if a[0] == '-':
295
 
            # option names must not be unicode
296
 
            a = str(a)
297
 
            optarg = None
298
 
            if a[1] == '-':
299
 
                mutter("  got option %r" % a)
300
 
                if '=' in a:
301
 
                    optname, optarg = a[2:].split('=', 1)
302
 
                else:
303
 
                    optname = a[2:]
304
 
                if optname not in cmd_options:
305
 
                    raise BzrCommandError('unknown long option %r for command %s' 
306
 
                            % (a, command.name))
307
 
            else:
308
 
                shortopt = a[1:]
309
 
                if shortopt in Option.SHORT_OPTIONS:
310
 
                    # Multi-character options must have a space to delimit
311
 
                    # their value
312
 
                    # ^^^ what does this mean? mbp 20051014
313
 
                    optname = Option.SHORT_OPTIONS[shortopt].name
314
 
                else:
315
 
                    # Single character short options, can be chained,
316
 
                    # and have their value appended to their name
317
 
                    shortopt = a[1:2]
318
 
                    if shortopt not in Option.SHORT_OPTIONS:
319
 
                        # We didn't find the multi-character name, and we
320
 
                        # didn't find the single char name
321
 
                        raise BzrError('unknown short option %r' % a)
322
 
                    optname = Option.SHORT_OPTIONS[shortopt].name
323
 
 
324
 
                    if a[2:]:
325
 
                        # There are extra things on this option
326
 
                        # see if it is the value, or if it is another
327
 
                        # short option
328
 
                        optargfn = Option.OPTIONS[optname].type
329
 
                        if optargfn is None:
330
 
                            # This option does not take an argument, so the
331
 
                            # next entry is another short option, pack it back
332
 
                            # into the list
333
 
                            argv.insert(0, '-' + a[2:])
334
 
                        else:
335
 
                            # This option takes an argument, so pack it
336
 
                            # into the array
337
 
                            optarg = a[2:]
338
 
            
339
 
            if optname in opts:
340
 
                # XXX: Do we ever want to support this, e.g. for -r?
341
 
                raise BzrError('repeated option %r' % a)
342
 
                
343
 
            option_obj = cmd_options[optname]
344
 
            optargfn = option_obj.type
345
 
            if optargfn:
346
 
                if optarg == None:
347
 
                    if not argv:
348
 
                        raise BzrError('option %r needs an argument' % a)
349
 
                    else:
350
 
                        optarg = argv.pop(0)
351
 
                opts[optname] = optargfn(optarg)
352
 
            else:
353
 
                if optarg != None:
354
 
                    raise BzrError('option %r takes no argument' % optname)
355
 
                opts[optname] = True
356
 
        else:
357
 
            args.append(a)
 
358
    # TODO: make it a method of the Command?
 
359
    parser = option.get_optparser(command.options())
 
360
    if alias_argv is not None:
 
361
        args = alias_argv + argv
 
362
    else:
 
363
        args = argv
 
364
 
 
365
    options, args = parser.parse_args(args)
 
366
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if 
 
367
                 v is not option.OptionParser.DEFAULT_VALUE])
358
368
    return args, opts
359
369
 
360
370
 
385
395
                raise BzrCommandError("command %r needs one or more %s"
386
396
                        % (cmd, argname.upper()))
387
397
            argdict[argname + '_list'] = args[:-1]
388
 
            args[:-1] = []                
 
398
            args[:-1] = []
389
399
        else:
390
400
            # just a plain arg
391
401
            argname = ap
426
436
        os.remove(pfname)
427
437
 
428
438
 
 
439
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
 
440
    from bzrlib.lsprof import profile
 
441
    import cPickle
 
442
    ret, stats = profile(the_callable, *args, **kwargs)
 
443
    stats.sort()
 
444
    if filename is None:
 
445
        stats.pprint()
 
446
    else:
 
447
        stats.freeze()
 
448
        cPickle.dump(stats, open(filename, 'w'), 2)
 
449
        print 'Profile data written to %r.' % filename
 
450
    return ret
 
451
 
 
452
 
 
453
def get_alias(cmd):
 
454
    """Return an expanded alias, or None if no alias exists"""
 
455
    import bzrlib.config
 
456
    alias = bzrlib.config.GlobalConfig().get_alias(cmd)
 
457
    if (alias):
 
458
        return alias.split(' ')
 
459
    return None
 
460
 
 
461
 
429
462
def run_bzr(argv):
430
463
    """Execute a command.
431
464
 
434
467
    
435
468
    argv
436
469
       The command-line arguments, without the program name from argv[0]
 
470
       These should already be decoded. All library/test code calling
 
471
       run_bzr should be passing valid strings (don't need decoding).
437
472
    
438
473
    Returns a command status or raises an exception.
439
474
 
443
478
    --no-plugins
444
479
        Do not load plugin modules at all
445
480
 
 
481
    --no-aliases
 
482
        Do not allow aliases
 
483
 
446
484
    --builtin
447
485
        Only use builtin commands.  (Plugins are still allowed to change
448
486
        other behaviour.)
449
487
 
450
488
    --profile
451
 
        Run under the Python profiler.
 
489
        Run under the Python hotshot profiler.
 
490
 
 
491
    --lsprof
 
492
        Run under the Python lsprof profiler.
452
493
    """
453
 
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
 
494
    argv = list(argv)
454
495
 
455
 
    opt_profile = opt_no_plugins = opt_builtin = False
 
496
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
 
497
                opt_no_aliases = False
 
498
    opt_lsprof_file = None
456
499
 
457
500
    # --no-plugins is handled specially at a very early stage. We need
458
501
    # to load plugins before doing other command parsing so that they
459
502
    # can override commands, but this needs to happen first.
460
503
 
461
 
    for a in argv:
 
504
    argv_copy = []
 
505
    i = 0
 
506
    while i < len(argv):
 
507
        a = argv[i]
462
508
        if a == '--profile':
463
509
            opt_profile = True
 
510
        elif a == '--lsprof':
 
511
            opt_lsprof = True
 
512
        elif a == '--lsprof-file':
 
513
            opt_lsprof = True
 
514
            opt_lsprof_file = argv[i + 1]
 
515
            i += 1
464
516
        elif a == '--no-plugins':
465
517
            opt_no_plugins = True
 
518
        elif a == '--no-aliases':
 
519
            opt_no_aliases = True
466
520
        elif a == '--builtin':
467
521
            opt_builtin = True
 
522
        elif a in ('--quiet', '-q'):
 
523
            be_quiet()
468
524
        else:
469
 
            break
470
 
        argv.remove(a)
 
525
            argv_copy.append(a)
 
526
        i += 1
471
527
 
472
 
    if (not argv) or (argv[0] == '--help'):
473
 
        from bzrlib.help import help
474
 
        if len(argv) > 1:
475
 
            help(argv[1])
476
 
        else:
477
 
            help()
 
528
    argv = argv_copy
 
529
    if (not argv):
 
530
        from bzrlib.builtins import cmd_help
 
531
        cmd_help().run_argv_aliases([])
478
532
        return 0
479
533
 
480
534
    if argv[0] == '--version':
481
 
        from bzrlib.builtins import show_version
 
535
        from bzrlib.version import show_version
482
536
        show_version()
483
537
        return 0
484
538
        
485
539
    if not opt_no_plugins:
486
540
        from bzrlib.plugin import load_plugins
487
541
        load_plugins()
488
 
 
489
 
    cmd = str(argv.pop(0))
 
542
    else:
 
543
        from bzrlib.plugin import disable_plugins
 
544
        disable_plugins()
 
545
 
 
546
    alias_argv = None
 
547
 
 
548
    if not opt_no_aliases:
 
549
        alias_argv = get_alias(argv[0])
 
550
        if alias_argv:
 
551
            alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
 
552
            argv[0] = alias_argv.pop(0)
 
553
 
 
554
    cmd = argv.pop(0)
 
555
    # We want only 'ascii' command names, but the user may have typed
 
556
    # in a Unicode name. In that case, they should just get a
 
557
    # 'command not found' error later.
490
558
 
491
559
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
492
 
 
493
 
    if opt_profile:
494
 
        ret = apply_profiled(cmd_obj.run_argv, argv)
 
560
    if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
 
561
        run = cmd_obj.run_argv
 
562
        run_argv = [argv]
495
563
    else:
496
 
        ret = cmd_obj.run_argv(argv)
497
 
    return ret or 0
 
564
        run = cmd_obj.run_argv_aliases
 
565
        run_argv = [argv, alias_argv]
 
566
 
 
567
    try:
 
568
        if opt_lsprof:
 
569
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
 
570
        elif opt_profile:
 
571
            ret = apply_profiled(run, *run_argv)
 
572
        else:
 
573
            ret = run(*run_argv)
 
574
        return ret or 0
 
575
    finally:
 
576
        # reset, in case we may do other commands later within the same process
 
577
        be_quiet(False)
 
578
 
 
579
def display_command(func):
 
580
    """Decorator that suppresses pipe/interrupt errors."""
 
581
    def ignore_pipe(*args, **kwargs):
 
582
        try:
 
583
            result = func(*args, **kwargs)
 
584
            sys.stdout.flush()
 
585
            return result
 
586
        except IOError, e:
 
587
            if getattr(e, 'errno', None) is None:
 
588
                raise
 
589
            if e.errno != errno.EPIPE:
 
590
                # Win32 raises IOError with errno=0 on a broken pipe
 
591
                if sys.platform != 'win32' or e.errno != 0:
 
592
                    raise
 
593
            pass
 
594
        except KeyboardInterrupt:
 
595
            pass
 
596
    return ignore_pipe
498
597
 
499
598
 
500
599
def main(argv):
501
600
    import bzrlib.ui
502
 
    bzrlib.trace.log_startup(argv)
503
 
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
504
 
 
505
 
    return run_bzr_catch_errors(argv[1:])
 
601
    from bzrlib.ui.text import TextUIFactory
 
602
    bzrlib.ui.ui_factory = TextUIFactory()
 
603
    argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
 
604
    ret = run_bzr_catch_errors(argv)
 
605
    mutter("return code %d", ret)
 
606
    return ret
506
607
 
507
608
 
508
609
def run_bzr_catch_errors(argv):
509
610
    try:
510
 
        try:
511
 
            return run_bzr(argv)
512
 
        finally:
513
 
            # do this here inside the exception wrappers to catch EPIPE
514
 
            sys.stdout.flush()
515
 
    except BzrCommandError, e:
516
 
        # command line syntax error, etc
517
 
        log_error(str(e))
518
 
        return 1
519
 
    except BzrError, e:
520
 
        bzrlib.trace.log_exception()
521
 
        return 1
522
 
    except AssertionError, e:
523
 
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
 
611
        return run_bzr(argv)
 
612
        # do this here inside the exception wrappers to catch EPIPE
 
613
        sys.stdout.flush()
 
614
    except Exception, e:
 
615
        # used to handle AssertionError and KeyboardInterrupt
 
616
        # specially here, but hopefully they're handled ok by the logger now
 
617
        bzrlib.trace.report_exception(sys.exc_info(), sys.stderr)
 
618
        if os.environ.get('BZR_PDB'):
 
619
            print '**** entering debugger'
 
620
            import pdb
 
621
            pdb.post_mortem(sys.exc_traceback)
524
622
        return 3
525
 
    except KeyboardInterrupt, e:
526
 
        bzrlib.trace.log_exception('interrupted')
527
 
        return 2
528
 
    except Exception, e:
529
 
        import errno
530
 
        if (isinstance(e, IOError) 
531
 
            and hasattr(e, 'errno')
532
 
            and e.errno == errno.EPIPE):
533
 
            bzrlib.trace.note('broken pipe')
534
 
            return 2
535
 
        else:
536
 
            ## import pdb
537
 
            ## pdb.pm()
538
 
            bzrlib.trace.log_exception()
539
 
            return 2
540
623
 
541
624
if __name__ == '__main__':
542
625
    sys.exit(main(sys.argv))