/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-08-30 05:30:43 UTC
  • Revision ID: mbp@sourcefrog.net-20050830053042-58932432ee958d1e
- make get_parent() be a method of Branch; add simple tests for it

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005 by Canonical Ltd
 
2
 
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
 
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
 
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
# TODO: probably should say which arguments are candidates for glob
 
19
# expansion on windows and do that at the command level.
 
20
 
 
21
# TODO: Help messages for options.
 
22
 
 
23
# TODO: Define arguments by objects, rather than just using names.
 
24
# Those objects can specify the expected type of the argument, which
 
25
# would help with validation and shell completion.
 
26
 
 
27
 
 
28
import sys
 
29
import os
 
30
 
 
31
import bzrlib
 
32
import bzrlib.trace
 
33
from bzrlib.trace import mutter, note, log_error, warning
 
34
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
35
from bzrlib.branch import find_branch
 
36
from bzrlib import BZRDIR
 
37
 
 
38
 
 
39
plugin_cmds = {}
 
40
 
 
41
 
 
42
def register_command(cmd):
 
43
    "Utility function to help register a command"
 
44
    global plugin_cmds
 
45
    k = cmd.__name__
 
46
    if k.startswith("cmd_"):
 
47
        k_unsquished = _unsquish_command_name(k)
 
48
    else:
 
49
        k_unsquished = k
 
50
    if not plugin_cmds.has_key(k_unsquished):
 
51
        plugin_cmds[k_unsquished] = cmd
 
52
        mutter('registered plugin command %s', k_unsquished)      
 
53
    else:
 
54
        log_error('Two plugins defined the same command: %r' % k)
 
55
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
56
 
 
57
 
 
58
def _squish_command_name(cmd):
 
59
    return 'cmd_' + cmd.replace('-', '_')
 
60
 
 
61
 
 
62
def _unsquish_command_name(cmd):
 
63
    assert cmd.startswith("cmd_")
 
64
    return cmd[4:].replace('_','-')
 
65
 
 
66
 
 
67
def _parse_revision_str(revstr):
 
68
    """This handles a revision string -> revno.
 
69
 
 
70
    This always returns a list.  The list will have one element for 
 
71
 
 
72
    It supports integers directly, but everything else it
 
73
    defers for passing to Branch.get_revision_info()
 
74
 
 
75
    >>> _parse_revision_str('234')
 
76
    [234]
 
77
    >>> _parse_revision_str('234..567')
 
78
    [234, 567]
 
79
    >>> _parse_revision_str('..')
 
80
    [None, None]
 
81
    >>> _parse_revision_str('..234')
 
82
    [None, 234]
 
83
    >>> _parse_revision_str('234..')
 
84
    [234, None]
 
85
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
86
    [234, 456, 789]
 
87
    >>> _parse_revision_str('234....789') # Error?
 
88
    [234, None, 789]
 
89
    >>> _parse_revision_str('revid:test@other.com-234234')
 
90
    ['revid:test@other.com-234234']
 
91
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
92
    ['revid:test@other.com-234234', 'revid:test@other.com-234235']
 
93
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
94
    ['revid:test@other.com-234234', 23]
 
95
    >>> _parse_revision_str('date:2005-04-12')
 
96
    ['date:2005-04-12']
 
97
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
98
    ['date:2005-04-12 12:24:33']
 
99
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
100
    ['date:2005-04-12T12:24:33']
 
101
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
102
    ['date:2005-04-12,12:24:33']
 
103
    >>> _parse_revision_str('-5..23')
 
104
    [-5, 23]
 
105
    >>> _parse_revision_str('-5')
 
106
    [-5]
 
107
    >>> _parse_revision_str('123a')
 
108
    ['123a']
 
109
    >>> _parse_revision_str('abc')
 
110
    ['abc']
 
111
    """
 
112
    import re
 
113
    old_format_re = re.compile('\d*:\d*')
 
114
    m = old_format_re.match(revstr)
 
115
    if m:
 
116
        warning('Colon separator for revision numbers is deprecated.'
 
117
                ' Use .. instead')
 
118
        revs = []
 
119
        for rev in revstr.split(':'):
 
120
            if rev:
 
121
                revs.append(int(rev))
 
122
            else:
 
123
                revs.append(None)
 
124
        return revs
 
125
    revs = []
 
126
    for x in revstr.split('..'):
 
127
        if not x:
 
128
            revs.append(None)
 
129
        else:
 
130
            try:
 
131
                revs.append(int(x))
 
132
            except ValueError:
 
133
                revs.append(x)
 
134
    return revs
 
135
 
 
136
 
 
137
def get_merge_type(typestring):
 
138
    """Attempt to find the merge class/factory associated with a string."""
 
139
    from merge import merge_types
 
140
    try:
 
141
        return merge_types[typestring][0]
 
142
    except KeyError:
 
143
        templ = '%s%%7s: %%s' % (' '*12)
 
144
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
145
        type_list = '\n'.join(lines)
 
146
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
147
            (typestring, type_list)
 
148
        raise BzrCommandError(msg)
 
149
    
 
150
 
 
151
def get_merge_type(typestring):
 
152
    """Attempt to find the merge class/factory associated with a string."""
 
153
    from merge import merge_types
 
154
    try:
 
155
        return merge_types[typestring][0]
 
156
    except KeyError:
 
157
        templ = '%s%%7s: %%s' % (' '*12)
 
158
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
159
        type_list = '\n'.join(lines)
 
160
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
161
            (typestring, type_list)
 
162
        raise BzrCommandError(msg)
 
163
    
 
164
 
 
165
 
 
166
def _get_cmd_dict(plugins_override=True):
 
167
    import bzrlib.builtins
 
168
    
 
169
    d = {}
 
170
    builtins = bzrlib.builtins.__dict__
 
171
    for name in builtins:
 
172
        if name.startswith("cmd_"):
 
173
            d[_unsquish_command_name(name)] = builtins[name]
 
174
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
175
    if plugins_override:
 
176
        d.update(plugin_cmds)
 
177
    else:
 
178
        d2 = plugin_cmds.copy()
 
179
        d2.update(d)
 
180
        d = d2
 
181
    return d
 
182
 
 
183
    
 
184
def get_all_cmds(plugins_override=True):
 
185
    """Return canonical name and class for all registered commands."""
 
186
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
187
        yield k,v
 
188
 
 
189
 
 
190
def get_cmd_class(cmd, plugins_override=True):
 
191
    """Return the canonical name and command class for a command.
 
192
    """
 
193
    cmd = str(cmd)                      # not unicode
 
194
 
 
195
    # first look up this command under the specified name
 
196
    cmds = _get_cmd_dict(plugins_override=plugins_override)
 
197
    mutter("all commands: %r", cmds.keys())
 
198
    try:
 
199
        return cmd, cmds[cmd]
 
200
    except KeyError:
 
201
        pass
 
202
 
 
203
    # look for any command which claims this as an alias
 
204
    for cmdname, cmdclass in cmds.iteritems():
 
205
        if cmd in cmdclass.aliases:
 
206
            return cmdname, cmdclass
 
207
 
 
208
    cmdclass = ExternalCommand.find_command(cmd)
 
209
    if cmdclass:
 
210
        return cmd, cmdclass
 
211
 
 
212
    raise BzrCommandError("unknown command %r" % cmd)
 
213
 
 
214
 
 
215
class Command(object):
 
216
    """Base class for commands.
 
217
 
 
218
    The docstring for an actual command should give a single-line
 
219
    summary, then a complete description of the command.  A grammar
 
220
    description will be inserted.
 
221
 
 
222
    takes_args
 
223
        List of argument forms, marked with whether they are optional,
 
224
        repeated, etc.
 
225
 
 
226
    takes_options
 
227
        List of options that may be given for this command.
 
228
 
 
229
    hidden
 
230
        If true, this command isn't advertised.
 
231
    """
 
232
    aliases = []
 
233
    
 
234
    takes_args = []
 
235
    takes_options = []
 
236
 
 
237
    hidden = False
 
238
    
 
239
    def __init__(self, options, arguments):
 
240
        """Construct and run the command.
 
241
 
 
242
        Sets self.status to the return value of run()."""
 
243
        assert isinstance(options, dict)
 
244
        assert isinstance(arguments, dict)
 
245
        cmdargs = options.copy()
 
246
        cmdargs.update(arguments)
 
247
        if self.__doc__ == Command.__doc__:
 
248
            from warnings import warn
 
249
            warn("No help message set for %r" % self)
 
250
        self.status = self.run(**cmdargs)
 
251
        if self.status is None:
 
252
            self.status = 0
 
253
 
 
254
    
 
255
    def run(self, *args, **kwargs):
 
256
        """Override this in sub-classes.
 
257
 
 
258
        This is invoked with the options and arguments bound to
 
259
        keyword parameters.
 
260
 
 
261
        Return 0 or None if the command was successful, or a shell
 
262
        error code if not.
 
263
        """
 
264
        raise NotImplementedError()
 
265
 
 
266
 
 
267
class ExternalCommand(Command):
 
268
    """Class to wrap external commands.
 
269
 
 
270
    We cheat a little here, when get_cmd_class() calls us we actually
 
271
    give it back an object we construct that has the appropriate path,
 
272
    help, options etc for the specified command.
 
273
 
 
274
    When run_bzr() tries to instantiate that 'class' it gets caught by
 
275
    the __call__ method, which we override to call the Command.__init__
 
276
    method. That then calls our run method which is pretty straight
 
277
    forward.
 
278
 
 
279
    The only wrinkle is that we have to map bzr's dictionary of options
 
280
    and arguments back into command line options and arguments for the
 
281
    script.
 
282
    """
 
283
 
 
284
    def find_command(cls, cmd):
 
285
        import os.path
 
286
        bzrpath = os.environ.get('BZRPATH', '')
 
287
 
 
288
        for dir in bzrpath.split(os.pathsep):
 
289
            path = os.path.join(dir, cmd)
 
290
            if os.path.isfile(path):
 
291
                return ExternalCommand(path)
 
292
 
 
293
        return None
 
294
 
 
295
    find_command = classmethod(find_command)
 
296
 
 
297
    def __init__(self, path):
 
298
        self.path = path
 
299
 
 
300
        pipe = os.popen('%s --bzr-usage' % path, 'r')
 
301
        self.takes_options = pipe.readline().split()
 
302
 
 
303
        for opt in self.takes_options:
 
304
            if not opt in OPTIONS:
 
305
                raise BzrError("Unknown option '%s' returned by external command %s"
 
306
                               % (opt, path))
 
307
 
 
308
        # TODO: Is there any way to check takes_args is valid here?
 
309
        self.takes_args = pipe.readline().split()
 
310
 
 
311
        if pipe.close() is not None:
 
312
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
 
313
 
 
314
        pipe = os.popen('%s --bzr-help' % path, 'r')
 
315
        self.__doc__ = pipe.read()
 
316
        if pipe.close() is not None:
 
317
            raise BzrError("Failed funning '%s --bzr-help'" % path)
 
318
 
 
319
    def __call__(self, options, arguments):
 
320
        Command.__init__(self, options, arguments)
 
321
        return self
 
322
 
 
323
    def run(self, **kargs):
 
324
        opts = []
 
325
        args = []
 
326
 
 
327
        keys = kargs.keys()
 
328
        keys.sort()
 
329
        for name in keys:
 
330
            optname = name.replace('_','-')
 
331
            value = kargs[name]
 
332
            if OPTIONS.has_key(optname):
 
333
                # it's an option
 
334
                opts.append('--%s' % optname)
 
335
                if value is not None and value is not True:
 
336
                    opts.append(str(value))
 
337
            else:
 
338
                # it's an arg, or arg list
 
339
                if type(value) is not list:
 
340
                    value = [value]
 
341
                for v in value:
 
342
                    if v is not None:
 
343
                        args.append(str(v))
 
344
 
 
345
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
 
346
        return self.status
 
347
 
 
348
 
 
349
 
 
350
def parse_spec(spec):
 
351
    """
 
352
    >>> parse_spec(None)
 
353
    [None, None]
 
354
    >>> parse_spec("./")
 
355
    ['./', None]
 
356
    >>> parse_spec("../@")
 
357
    ['..', -1]
 
358
    >>> parse_spec("../f/@35")
 
359
    ['../f', 35]
 
360
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
361
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
 
362
    """
 
363
    if spec is None:
 
364
        return [None, None]
 
365
    if '/@' in spec:
 
366
        parsed = spec.split('/@')
 
367
        assert len(parsed) == 2
 
368
        if parsed[1] == "":
 
369
            parsed[1] = -1
 
370
        else:
 
371
            try:
 
372
                parsed[1] = int(parsed[1])
 
373
            except ValueError:
 
374
                pass # We can allow stuff like ./@revid:blahblahblah
 
375
            else:
 
376
                assert parsed[1] >=0
 
377
    else:
 
378
        parsed = [spec, None]
 
379
    return parsed
 
380
 
 
381
 
 
382
 
 
383
 
 
384
# list of all available options; the rhs can be either None for an
 
385
# option that takes no argument, or a constructor function that checks
 
386
# the type.
 
387
OPTIONS = {
 
388
    'all':                    None,
 
389
    'diff-options':           str,
 
390
    'help':                   None,
 
391
    'file':                   unicode,
 
392
    'force':                  None,
 
393
    'format':                 unicode,
 
394
    'forward':                None,
 
395
    'message':                unicode,
 
396
    'no-recurse':             None,
 
397
    'profile':                None,
 
398
    'revision':               _parse_revision_str,
 
399
    'short':                  None,
 
400
    'show-ids':               None,
 
401
    'timezone':               str,
 
402
    'verbose':                None,
 
403
    'version':                None,
 
404
    'email':                  None,
 
405
    'unchanged':              None,
 
406
    'update':                 None,
 
407
    'long':                   None,
 
408
    'root':                   str,
 
409
    'no-backup':              None,
 
410
    'merge-type':             get_merge_type,
 
411
    'pattern':                str,
 
412
    }
 
413
 
 
414
SHORT_OPTIONS = {
 
415
    'F':                      'file', 
 
416
    'h':                      'help',
 
417
    'm':                      'message',
 
418
    'r':                      'revision',
 
419
    'v':                      'verbose',
 
420
    'l':                      'long',
 
421
}
 
422
 
 
423
 
 
424
def parse_args(argv):
 
425
    """Parse command line.
 
426
    
 
427
    Arguments and options are parsed at this level before being passed
 
428
    down to specific command handlers.  This routine knows, from a
 
429
    lookup table, something about the available options, what optargs
 
430
    they take, and which commands will accept them.
 
431
 
 
432
    >>> parse_args('--help'.split())
 
433
    ([], {'help': True})
 
434
    >>> parse_args('help -- --invalidcmd'.split())
 
435
    (['help', '--invalidcmd'], {})
 
436
    >>> parse_args('--version'.split())
 
437
    ([], {'version': True})
 
438
    >>> parse_args('status --all'.split())
 
439
    (['status'], {'all': True})
 
440
    >>> parse_args('commit --message=biter'.split())
 
441
    (['commit'], {'message': u'biter'})
 
442
    >>> parse_args('log -r 500'.split())
 
443
    (['log'], {'revision': [500]})
 
444
    >>> parse_args('log -r500..600'.split())
 
445
    (['log'], {'revision': [500, 600]})
 
446
    >>> parse_args('log -vr500..600'.split())
 
447
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
448
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
 
449
    (['log'], {'revision': ['v500', 600]})
 
450
    """
 
451
    args = []
 
452
    opts = {}
 
453
 
 
454
    argsover = False
 
455
    while argv:
 
456
        a = argv.pop(0)
 
457
        if not argsover and a[0] == '-':
 
458
            # option names must not be unicode
 
459
            a = str(a)
 
460
            optarg = None
 
461
            if a[1] == '-':
 
462
                if a == '--':
 
463
                    # We've received a standalone -- No more flags
 
464
                    argsover = True
 
465
                    continue
 
466
                mutter("  got option %r" % a)
 
467
                if '=' in a:
 
468
                    optname, optarg = a[2:].split('=', 1)
 
469
                else:
 
470
                    optname = a[2:]
 
471
                if optname not in OPTIONS:
 
472
                    raise BzrError('unknown long option %r' % a)
 
473
            else:
 
474
                shortopt = a[1:]
 
475
                if shortopt in SHORT_OPTIONS:
 
476
                    # Multi-character options must have a space to delimit
 
477
                    # their value
 
478
                    optname = SHORT_OPTIONS[shortopt]
 
479
                else:
 
480
                    # Single character short options, can be chained,
 
481
                    # and have their value appended to their name
 
482
                    shortopt = a[1:2]
 
483
                    if shortopt not in SHORT_OPTIONS:
 
484
                        # We didn't find the multi-character name, and we
 
485
                        # didn't find the single char name
 
486
                        raise BzrError('unknown short option %r' % a)
 
487
                    optname = SHORT_OPTIONS[shortopt]
 
488
 
 
489
                    if a[2:]:
 
490
                        # There are extra things on this option
 
491
                        # see if it is the value, or if it is another
 
492
                        # short option
 
493
                        optargfn = OPTIONS[optname]
 
494
                        if optargfn is None:
 
495
                            # This option does not take an argument, so the
 
496
                            # next entry is another short option, pack it back
 
497
                            # into the list
 
498
                            argv.insert(0, '-' + a[2:])
 
499
                        else:
 
500
                            # This option takes an argument, so pack it
 
501
                            # into the array
 
502
                            optarg = a[2:]
 
503
            
 
504
            if optname in opts:
 
505
                # XXX: Do we ever want to support this, e.g. for -r?
 
506
                raise BzrError('repeated option %r' % a)
 
507
                
 
508
            optargfn = OPTIONS[optname]
 
509
            if optargfn:
 
510
                if optarg == None:
 
511
                    if not argv:
 
512
                        raise BzrError('option %r needs an argument' % a)
 
513
                    else:
 
514
                        optarg = argv.pop(0)
 
515
                opts[optname] = optargfn(optarg)
 
516
            else:
 
517
                if optarg != None:
 
518
                    raise BzrError('option %r takes no argument' % optname)
 
519
                opts[optname] = True
 
520
        else:
 
521
            args.append(a)
 
522
 
 
523
    return args, opts
 
524
 
 
525
 
 
526
 
 
527
 
 
528
def _match_argform(cmd, takes_args, args):
 
529
    argdict = {}
 
530
 
 
531
    # step through args and takes_args, allowing appropriate 0-many matches
 
532
    for ap in takes_args:
 
533
        argname = ap[:-1]
 
534
        if ap[-1] == '?':
 
535
            if args:
 
536
                argdict[argname] = args.pop(0)
 
537
        elif ap[-1] == '*': # all remaining arguments
 
538
            if args:
 
539
                argdict[argname + '_list'] = args[:]
 
540
                args = []
 
541
            else:
 
542
                argdict[argname + '_list'] = None
 
543
        elif ap[-1] == '+':
 
544
            if not args:
 
545
                raise BzrCommandError("command %r needs one or more %s"
 
546
                        % (cmd, argname.upper()))
 
547
            else:
 
548
                argdict[argname + '_list'] = args[:]
 
549
                args = []
 
550
        elif ap[-1] == '$': # all but one
 
551
            if len(args) < 2:
 
552
                raise BzrCommandError("command %r needs one or more %s"
 
553
                        % (cmd, argname.upper()))
 
554
            argdict[argname + '_list'] = args[:-1]
 
555
            args[:-1] = []                
 
556
        else:
 
557
            # just a plain arg
 
558
            argname = ap
 
559
            if not args:
 
560
                raise BzrCommandError("command %r requires argument %s"
 
561
                        % (cmd, argname.upper()))
 
562
            else:
 
563
                argdict[argname] = args.pop(0)
 
564
            
 
565
    if args:
 
566
        raise BzrCommandError("extra argument to command %s: %s"
 
567
                              % (cmd, args[0]))
 
568
 
 
569
    return argdict
 
570
 
 
571
 
 
572
 
 
573
def run_bzr(argv):
 
574
    """Execute a command.
 
575
 
 
576
    This is similar to main(), but without all the trappings for
 
577
    logging and error handling.  
 
578
    
 
579
    argv
 
580
       The command-line arguments, without the program name from argv[0]
 
581
    
 
582
    Returns a command status or raises an exception.
 
583
 
 
584
    Special master options: these must come before the command because
 
585
    they control how the command is interpreted.
 
586
 
 
587
    --no-plugins
 
588
        Do not load plugin modules at all
 
589
 
 
590
    --builtin
 
591
        Only use builtin commands.  (Plugins are still allowed to change
 
592
        other behaviour.)
 
593
 
 
594
    --profile
 
595
        Run under the Python profiler.
 
596
    """
 
597
    
 
598
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
 
599
 
 
600
    opt_profile = opt_no_plugins = opt_builtin = False
 
601
 
 
602
    # --no-plugins is handled specially at a very early stage. We need
 
603
    # to load plugins before doing other command parsing so that they
 
604
    # can override commands, but this needs to happen first.
 
605
 
 
606
    for a in argv[:]:
 
607
        if a == '--profile':
 
608
            opt_profile = True
 
609
        elif a == '--no-plugins':
 
610
            opt_no_plugins = True
 
611
        elif a == '--builtin':
 
612
            opt_builtin = True
 
613
        else:
 
614
            break
 
615
        argv.remove(a)
 
616
 
 
617
    if not opt_no_plugins:
 
618
        from bzrlib.plugin import load_plugins
 
619
        load_plugins()
 
620
 
 
621
    args, opts = parse_args(argv)
 
622
 
 
623
    if 'help' in opts:
 
624
        from bzrlib.help import help
 
625
        if args:
 
626
            help(args[0])
 
627
        else:
 
628
            help()
 
629
        return 0            
 
630
        
 
631
    if 'version' in opts:
 
632
        from bzrlib.builtins import show_version
 
633
        show_version()
 
634
        return 0
 
635
    
 
636
    if not args:
 
637
        from bzrlib.help import help
 
638
        help(None)
 
639
        return 0
 
640
    
 
641
    cmd = str(args.pop(0))
 
642
 
 
643
    canonical_cmd, cmd_class = \
 
644
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
 
645
 
 
646
    # check options are reasonable
 
647
    allowed = cmd_class.takes_options
 
648
    for oname in opts:
 
649
        if oname not in allowed:
 
650
            raise BzrCommandError("option '--%s' is not allowed for command %r"
 
651
                                  % (oname, cmd))
 
652
 
 
653
    # mix arguments and options into one dictionary
 
654
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
 
655
    cmdopts = {}
 
656
    for k, v in opts.items():
 
657
        cmdopts[k.replace('-', '_')] = v
 
658
 
 
659
    if opt_profile:
 
660
        import hotshot, tempfile
 
661
        pffileno, pfname = tempfile.mkstemp()
 
662
        try:
 
663
            prof = hotshot.Profile(pfname)
 
664
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
 
665
            prof.close()
 
666
 
 
667
            import hotshot.stats
 
668
            stats = hotshot.stats.load(pfname)
 
669
            #stats.strip_dirs()
 
670
            stats.sort_stats('time')
 
671
            ## XXX: Might like to write to stderr or the trace file instead but
 
672
            ## print_stats seems hardcoded to stdout
 
673
            stats.print_stats(20)
 
674
            
 
675
            return ret.status
 
676
 
 
677
        finally:
 
678
            os.close(pffileno)
 
679
            os.remove(pfname)
 
680
    else:
 
681
        return cmd_class(cmdopts, cmdargs).status 
 
682
 
 
683
 
 
684
def main(argv):
 
685
    import bzrlib.ui
 
686
    bzrlib.trace.log_startup(argv)
 
687
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
 
688
 
 
689
    try:
 
690
        try:
 
691
            return run_bzr(argv[1:])
 
692
        finally:
 
693
            # do this here inside the exception wrappers to catch EPIPE
 
694
            sys.stdout.flush()
 
695
    except BzrCommandError, e:
 
696
        # command line syntax error, etc
 
697
        log_error(str(e))
 
698
        return 1
 
699
    except BzrError, e:
 
700
        bzrlib.trace.log_exception()
 
701
        return 1
 
702
    except AssertionError, e:
 
703
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
 
704
        return 3
 
705
    except KeyboardInterrupt, e:
 
706
        bzrlib.trace.note('interrupted')
 
707
        return 2
 
708
    except Exception, e:
 
709
        import errno
 
710
        if (isinstance(e, IOError) 
 
711
            and hasattr(e, 'errno')
 
712
            and e.errno == errno.EPIPE):
 
713
            bzrlib.trace.note('broken pipe')
 
714
            return 2
 
715
        else:
 
716
            bzrlib.trace.log_exception()
 
717
            return 2
 
718
 
 
719
 
 
720
if __name__ == '__main__':
 
721
    sys.exit(main(sys.argv))