/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: Lalo Martins
  • Date: 2005-09-09 11:37:44 UTC
  • mto: (1185.1.22)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: lalo@exoweb.net-20050909113744-22f870db25a9e5f5
getting rid of everything that calls the Branch constructor directly

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