~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-09-30 05:56:05 UTC
  • mto: (1185.14.2)
  • mto: This revision was merged to the branch mainline in revision 1396.
  • Revision ID: mbp@sourcefrog.net-20050930055605-a2c534529b392a7d
- fix upgrade for transport changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2004, 2005 by Canonical Ltd
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
#
 
12
 
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
18
# TODO: probably should say which arguments are candidates for glob
19
19
# expansion on windows and do that at the command level.
20
20
 
21
 
# TODO: Define arguments by objects, rather than just using names.
22
 
# Those objects can specify the expected type of the argument, which
23
 
# would help with validation and shell completion.  They could also provide
24
 
# help/explanation for that argument in a structured way.
25
 
 
26
 
# TODO: Specific "examples" property on commands for consistent formatting.
27
 
 
28
 
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
29
 
# the profile output behind so it can be interactively examined?
30
 
 
 
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
# TODO: Help messages for options.
 
29
 
 
30
# TODO: Define arguments by objects, rather than just using names.
 
31
# Those objects can specify the expected type of the argument, which
 
32
# would help with validation and shell completion.
 
33
 
 
34
 
 
35
 
 
36
import sys
31
37
import os
32
 
import sys
33
 
 
34
 
from bzrlib.lazy_import import lazy_import
35
 
lazy_import(globals(), """
36
 
import codecs
37
 
import errno
38
38
from warnings import warn
 
39
from inspect import getdoc
39
40
 
40
41
import bzrlib
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
57
 
from bzrlib.option import Option
58
 
 
 
42
import bzrlib.trace
 
43
from bzrlib.trace import mutter, note, log_error, warning
 
44
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
 
45
from bzrlib.revisionspec import RevisionSpec
 
46
from bzrlib import BZRDIR
59
47
 
60
48
plugin_cmds = {}
61
49
 
62
50
 
63
 
def register_command(cmd, decorate=False):
64
 
    """Utility function to help register a command
65
 
 
66
 
    :param cmd: Command subclass to register
67
 
    :param decorate: If true, allow overriding an existing command
68
 
        of the same name; the old command is returned by this function.
69
 
        Otherwise it is an error to try to override an existing command.
70
 
    """
 
51
def register_command(cmd):
 
52
    "Utility function to help register a command"
71
53
    global plugin_cmds
72
54
    k = cmd.__name__
73
55
    if k.startswith("cmd_"):
74
56
        k_unsquished = _unsquish_command_name(k)
75
57
    else:
76
58
        k_unsquished = k
77
 
    if k_unsquished not in plugin_cmds:
78
 
        plugin_cmds[k_unsquished] = cmd
79
 
        ## trace.mutter('registered plugin command %s', k_unsquished)
80
 
        if decorate and k_unsquished in builtin_command_names():
81
 
            return _builtin_commands()[k_unsquished]
82
 
    elif decorate:
83
 
        result = plugin_cmds[k_unsquished]
84
 
        plugin_cmds[k_unsquished] = cmd
85
 
        return result
 
59
    if not plugin_cmds.has_key(k_unsquished):
 
60
        plugin_cmds[k_unsquished] = cmd
 
61
        mutter('registered plugin command %s', k_unsquished)      
86
62
    else:
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__])
 
63
        log_error('Two plugins defined the same command: %r' % k)
 
64
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
89
65
 
90
66
 
91
67
def _squish_command_name(cmd):
97
73
    return cmd[4:].replace('_','-')
98
74
 
99
75
 
 
76
def _parse_revision_str(revstr):
 
77
    """This handles a revision string -> revno.
 
78
 
 
79
    This always returns a list.  The list will have one element for
 
80
    each revision.
 
81
 
 
82
    >>> _parse_revision_str('234')
 
83
    [<RevisionSpec_int 234>]
 
84
    >>> _parse_revision_str('234..567')
 
85
    [<RevisionSpec_int 234>, <RevisionSpec_int 567>]
 
86
    >>> _parse_revision_str('..')
 
87
    [<RevisionSpec None>, <RevisionSpec None>]
 
88
    >>> _parse_revision_str('..234')
 
89
    [<RevisionSpec None>, <RevisionSpec_int 234>]
 
90
    >>> _parse_revision_str('234..')
 
91
    [<RevisionSpec_int 234>, <RevisionSpec None>]
 
92
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
93
    [<RevisionSpec_int 234>, <RevisionSpec_int 456>, <RevisionSpec_int 789>]
 
94
    >>> _parse_revision_str('234....789') # Error?
 
95
    [<RevisionSpec_int 234>, <RevisionSpec None>, <RevisionSpec_int 789>]
 
96
    >>> _parse_revision_str('revid:test@other.com-234234')
 
97
    [<RevisionSpec_revid revid:test@other.com-234234>]
 
98
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
99
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
 
100
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
101
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_int 23>]
 
102
    >>> _parse_revision_str('date:2005-04-12')
 
103
    [<RevisionSpec_date date:2005-04-12>]
 
104
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
105
    [<RevisionSpec_date date:2005-04-12 12:24:33>]
 
106
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
107
    [<RevisionSpec_date date:2005-04-12T12:24:33>]
 
108
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
109
    [<RevisionSpec_date date:2005-04-12,12:24:33>]
 
110
    >>> _parse_revision_str('-5..23')
 
111
    [<RevisionSpec_int -5>, <RevisionSpec_int 23>]
 
112
    >>> _parse_revision_str('-5')
 
113
    [<RevisionSpec_int -5>]
 
114
    >>> _parse_revision_str('123a')
 
115
    Traceback (most recent call last):
 
116
      ...
 
117
    BzrError: No namespace registered for string: '123a'
 
118
    >>> _parse_revision_str('abc')
 
119
    Traceback (most recent call last):
 
120
      ...
 
121
    BzrError: No namespace registered for string: 'abc'
 
122
    """
 
123
    import re
 
124
    old_format_re = re.compile('\d*:\d*')
 
125
    m = old_format_re.match(revstr)
 
126
    revs = []
 
127
    if m:
 
128
        warning('Colon separator for revision numbers is deprecated.'
 
129
                ' Use .. instead')
 
130
        for rev in revstr.split(':'):
 
131
            if rev:
 
132
                revs.append(RevisionSpec(int(rev)))
 
133
            else:
 
134
                revs.append(RevisionSpec(None))
 
135
    else:
 
136
        for x in revstr.split('..'):
 
137
            if not x:
 
138
                revs.append(RevisionSpec(None))
 
139
            else:
 
140
                revs.append(RevisionSpec(x))
 
141
    return revs
 
142
 
 
143
 
100
144
def _builtin_commands():
101
145
    import bzrlib.builtins
102
146
    r = {}
103
147
    builtins = bzrlib.builtins.__dict__
104
148
    for name in builtins:
105
149
        if name.startswith("cmd_"):
106
 
            real_name = _unsquish_command_name(name)
 
150
            real_name = _unsquish_command_name(name)        
107
151
            r[real_name] = builtins[name]
108
152
    return r
 
153
 
109
154
            
110
155
 
111
156
def builtin_command_names():
139
184
    """
140
185
    from bzrlib.externalcommand import ExternalCommand
141
186
 
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.
 
187
    cmd_name = str(cmd_name)            # not unicode
146
188
 
147
189
    # first look up this command under the specified name
148
190
    cmds = _get_cmd_dict(plugins_override=plugins_override)
160
202
    if cmd_obj:
161
203
        return cmd_obj
162
204
 
163
 
    raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
 
205
    raise BzrCommandError("unknown command %r" % cmd_name)
164
206
 
165
207
 
166
208
class Command(object):
188
230
        List of argument forms, marked with whether they are optional,
189
231
        repeated, etc.
190
232
 
191
 
                Examples:
192
 
 
193
 
                ['to_location', 'from_branch?', 'file*']
194
 
 
195
 
                'to_location' is required
196
 
                'from_branch' is optional
197
 
                'file' can be specified 0 or more times
198
 
 
199
233
    takes_options
200
 
        List of options that may be given for this command.  These can
201
 
        be either strings, referring to globally-defined options,
202
 
        or option objects.  Retrieve through options().
 
234
        List of options that may be given for this command.
203
235
 
204
236
    hidden
205
237
        If true, this command isn't advertised.  This is typically
206
238
        for commands intended for expert users.
207
 
 
208
 
    encoding_type
209
 
        Command objects will get a 'outf' attribute, which has been
210
 
        setup to properly handle encoding of unicode strings.
211
 
        encoding_type determines what will happen when characters cannot
212
 
        be encoded
213
 
            strict - abort if we cannot decode
214
 
            replace - put in a bogus character (typically '?')
215
 
            exact - do not encode sys.stdout
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
 
 
223
239
    """
224
240
    aliases = []
 
241
    
225
242
    takes_args = []
226
243
    takes_options = []
227
 
    encoding_type = 'strict'
228
244
 
229
245
    hidden = False
230
246
    
233
249
        if self.__doc__ == Command.__doc__:
234
250
            warn("No help message set for %r" % self)
235
251
 
236
 
    def options(self):
237
 
        """Return dict of valid options for this command.
238
 
 
239
 
        Maps from long option name to option object."""
240
 
        r = dict()
241
 
        r['help'] = option.Option.OPTIONS['help']
242
 
        for o in self.takes_options:
243
 
            if isinstance(o, basestring):
244
 
                o = option.Option.OPTIONS[o]
245
 
            r[o.name] = o
246
 
        return r
247
 
 
248
 
    def _setup_outf(self):
249
 
        """Return a file linked to stdout, which has proper encoding."""
250
 
        assert self.encoding_type in ['strict', 'exact', 'replace']
251
 
 
252
 
        # Originally I was using self.stdout, but that looks
253
 
        # *way* too much like sys.stdout
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)
261
 
            self.outf = sys.stdout
262
 
            return
263
 
 
264
 
        output_encoding = osutils.get_terminal_encoding()
265
 
 
266
 
        # use 'replace' so that we don't abort if trying to write out
267
 
        # in e.g. the default C locale.
268
 
        self.outf = codecs.getwriter(output_encoding)(sys.stdout, errors=self.encoding_type)
269
 
        # For whatever reason codecs.getwriter() does not advertise its encoding
270
 
        # it just returns the encoding of the wrapped file, which is completely
271
 
        # bogus. So set the attribute, so we can find the correct encoding later.
272
 
        self.outf.encoding = output_encoding
273
 
 
274
 
    @deprecated_method(zero_eight)
 
252
 
275
253
    def run_argv(self, argv):
276
 
        """Parse command line and run.
277
 
        
278
 
        See run_argv_aliases for the 0.8 and beyond api.
279
 
        """
280
 
        return self.run_argv_aliases(argv)
 
254
        """Parse command line and run."""
 
255
        args, opts = parse_args(argv)
281
256
 
282
 
    def run_argv_aliases(self, argv, alias_argv=None):
283
 
        """Parse the command line and run with extra aliases in alias_argv."""
284
 
        if argv is None:
285
 
            warn("Passing None for [] is deprecated from bzrlib 0.10",
286
 
                 DeprecationWarning, stacklevel=2)
287
 
            argv = []
288
 
        args, opts = parse_args(self, argv, alias_argv)
289
257
        if 'help' in opts:  # e.g. bzr add --help
290
258
            from bzrlib.help import help_on_command
291
259
            help_on_command(self.name())
292
260
            return 0
 
261
 
 
262
        # check options are reasonable
 
263
        allowed = self.takes_options
 
264
        for oname in opts:
 
265
            if oname not in allowed:
 
266
                raise BzrCommandError("option '--%s' is not allowed for command %r"
 
267
                                      % (oname, self.name()))
 
268
 
293
269
        # mix arguments and options into one dictionary
294
270
        cmdargs = _match_argform(self.name(), self.takes_args, args)
295
271
        cmdopts = {}
299
275
        all_cmd_args = cmdargs.copy()
300
276
        all_cmd_args.update(cmdopts)
301
277
 
302
 
        self._setup_outf()
303
 
 
304
278
        return self.run(**all_cmd_args)
 
279
 
305
280
    
306
281
    def run(self):
307
282
        """Actually run the command.
313
288
        shell error code if not.  It's OK for this method to allow
314
289
        an exception to raise up.
315
290
        """
316
 
        raise NotImplementedError('no implementation of command %r'
317
 
                                  % self.name())
 
291
        raise NotImplementedError()
 
292
 
318
293
 
319
294
    def help(self):
320
295
        """Return help message for this class."""
321
 
        from inspect import getdoc
322
296
        if self.__doc__ is Command.__doc__:
323
297
            return None
324
298
        return getdoc(self)
326
300
    def name(self):
327
301
        return _unsquish_command_name(self.__class__.__name__)
328
302
 
329
 
    def plugin_name(self):
330
 
        """Get the name of the plugin that provides this command.
331
 
 
332
 
        :return: The name of the plugin or None if the command is builtin.
333
 
        """
334
 
        mod_parts = self.__module__.split('.')
335
 
        if len(mod_parts) >= 3 and mod_parts[1] == 'plugins':
336
 
            return mod_parts[2]
337
 
        else:
338
 
            return None
339
 
 
340
 
 
341
 
# Technically, this function hasn't been use in a *really* long time
342
 
# but we are only deprecating it now.
343
 
@deprecated_function(zero_eleven)
 
303
 
344
304
def parse_spec(spec):
345
305
    """
346
306
    >>> parse_spec(None)
372
332
        parsed = [spec, None]
373
333
    return parsed
374
334
 
375
 
def parse_args(command, argv, alias_argv=None):
 
335
 
 
336
# list of all available options; the rhs can be either None for an
 
337
# option that takes no argument, or a constructor function that checks
 
338
# the type.
 
339
OPTIONS = {
 
340
    'all':                    None,
 
341
    'basis':                  str,
 
342
    'diff-options':           str,
 
343
    'help':                   None,
 
344
    'file':                   unicode,
 
345
    'force':                  None,
 
346
    'format':                 unicode,
 
347
    'forward':                None,
 
348
    'message':                unicode,
 
349
    'no-recurse':             None,
 
350
    'profile':                None,
 
351
    'revision':               _parse_revision_str,
 
352
    'short':                  None,
 
353
    'show-ids':               None,
 
354
    'timezone':               str,
 
355
    'verbose':                None,
 
356
    'version':                None,
 
357
    'email':                  None,
 
358
    'unchanged':              None,
 
359
    'update':                 None,
 
360
    'long':                   None,
 
361
    'root':                   str,
 
362
    'no-backup':              None,
 
363
    'pattern':                str,
 
364
    }
 
365
 
 
366
SHORT_OPTIONS = {
 
367
    'F':                      'file', 
 
368
    'h':                      'help',
 
369
    'm':                      'message',
 
370
    'r':                      'revision',
 
371
    'v':                      'verbose',
 
372
    'l':                      'long',
 
373
}
 
374
 
 
375
 
 
376
def parse_args(argv):
376
377
    """Parse command line.
377
378
    
378
379
    Arguments and options are parsed at this level before being passed
379
380
    down to specific command handlers.  This routine knows, from a
380
381
    lookup table, something about the available options, what optargs
381
382
    they take, and which commands will accept them.
 
383
 
 
384
    >>> parse_args('--help'.split())
 
385
    ([], {'help': True})
 
386
    >>> parse_args('help -- --invalidcmd'.split())
 
387
    (['help', '--invalidcmd'], {})
 
388
    >>> parse_args('--version'.split())
 
389
    ([], {'version': True})
 
390
    >>> parse_args('status --all'.split())
 
391
    (['status'], {'all': True})
 
392
    >>> parse_args('commit --message=biter'.split())
 
393
    (['commit'], {'message': u'biter'})
 
394
    >>> parse_args('log -r 500'.split())
 
395
    (['log'], {'revision': [<RevisionSpec_int 500>]})
 
396
    >>> parse_args('log -r500..600'.split())
 
397
    (['log'], {'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
 
398
    >>> parse_args('log -vr500..600'.split())
 
399
    (['log'], {'verbose': True, 'revision': [<RevisionSpec_int 500>, <RevisionSpec_int 600>]})
 
400
    >>> parse_args('log -rrevno:500..600'.split()) #the r takes an argument
 
401
    (['log'], {'revision': [<RevisionSpec_revno revno:500>, <RevisionSpec_int 600>]})
382
402
    """
383
 
    # TODO: make it a method of the Command?
384
 
    parser = option.get_optparser(command.options())
385
 
    if alias_argv is not None:
386
 
        args = alias_argv + argv
387
 
    else:
388
 
        args = argv
389
 
 
390
 
    options, args = parser.parse_args(args)
391
 
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
392
 
                 v is not option.OptionParser.DEFAULT_VALUE])
 
403
    args = []
 
404
    opts = {}
 
405
 
 
406
    argsover = False
 
407
    while argv:
 
408
        a = argv.pop(0)
 
409
        if not argsover and a[0] == '-':
 
410
            # option names must not be unicode
 
411
            a = str(a)
 
412
            optarg = None
 
413
            if a[1] == '-':
 
414
                if a == '--':
 
415
                    # We've received a standalone -- No more flags
 
416
                    argsover = True
 
417
                    continue
 
418
                mutter("  got option %r" % a)
 
419
                if '=' in a:
 
420
                    optname, optarg = a[2:].split('=', 1)
 
421
                else:
 
422
                    optname = a[2:]
 
423
                if optname not in OPTIONS:
 
424
                    raise BzrError('unknown long option %r' % a)
 
425
            else:
 
426
                shortopt = a[1:]
 
427
                if shortopt in SHORT_OPTIONS:
 
428
                    # Multi-character options must have a space to delimit
 
429
                    # their value
 
430
                    optname = SHORT_OPTIONS[shortopt]
 
431
                else:
 
432
                    # Single character short options, can be chained,
 
433
                    # and have their value appended to their name
 
434
                    shortopt = a[1:2]
 
435
                    if shortopt not in SHORT_OPTIONS:
 
436
                        # We didn't find the multi-character name, and we
 
437
                        # didn't find the single char name
 
438
                        raise BzrError('unknown short option %r' % a)
 
439
                    optname = SHORT_OPTIONS[shortopt]
 
440
 
 
441
                    if a[2:]:
 
442
                        # There are extra things on this option
 
443
                        # see if it is the value, or if it is another
 
444
                        # short option
 
445
                        optargfn = OPTIONS[optname]
 
446
                        if optargfn is None:
 
447
                            # This option does not take an argument, so the
 
448
                            # next entry is another short option, pack it back
 
449
                            # into the list
 
450
                            argv.insert(0, '-' + a[2:])
 
451
                        else:
 
452
                            # This option takes an argument, so pack it
 
453
                            # into the array
 
454
                            optarg = a[2:]
 
455
            
 
456
            if optname in opts:
 
457
                # XXX: Do we ever want to support this, e.g. for -r?
 
458
                raise BzrError('repeated option %r' % a)
 
459
                
 
460
            optargfn = OPTIONS[optname]
 
461
            if optargfn:
 
462
                if optarg == None:
 
463
                    if not argv:
 
464
                        raise BzrError('option %r needs an argument' % a)
 
465
                    else:
 
466
                        optarg = argv.pop(0)
 
467
                opts[optname] = optargfn(optarg)
 
468
            else:
 
469
                if optarg != None:
 
470
                    raise BzrError('option %r takes no argument' % optname)
 
471
                opts[optname] = True
 
472
        else:
 
473
            args.append(a)
 
474
 
393
475
    return args, opts
394
476
 
395
477
 
 
478
 
 
479
 
396
480
def _match_argform(cmd, takes_args, args):
397
481
    argdict = {}
398
482
 
410
494
                argdict[argname + '_list'] = None
411
495
        elif ap[-1] == '+':
412
496
            if not args:
413
 
                raise errors.BzrCommandError("command %r needs one or more %s"
414
 
                                             % (cmd, argname.upper()))
 
497
                raise BzrCommandError("command %r needs one or more %s"
 
498
                        % (cmd, argname.upper()))
415
499
            else:
416
500
                argdict[argname + '_list'] = args[:]
417
501
                args = []
418
502
        elif ap[-1] == '$': # all but one
419
503
            if len(args) < 2:
420
 
                raise errors.BzrCommandError("command %r needs one or more %s"
421
 
                                             % (cmd, argname.upper()))
 
504
                raise BzrCommandError("command %r needs one or more %s"
 
505
                        % (cmd, argname.upper()))
422
506
            argdict[argname + '_list'] = args[:-1]
423
 
            args[:-1] = []
 
507
            args[:-1] = []                
424
508
        else:
425
509
            # just a plain arg
426
510
            argname = ap
427
511
            if not args:
428
 
                raise errors.BzrCommandError("command %r requires argument %s"
429
 
                               % (cmd, argname.upper()))
 
512
                raise BzrCommandError("command %r requires argument %s"
 
513
                        % (cmd, argname.upper()))
430
514
            else:
431
515
                argdict[argname] = args.pop(0)
432
516
            
433
517
    if args:
434
 
        raise errors.BzrCommandError("extra argument to command %s: %s"
435
 
                                     % (cmd, args[0]))
 
518
        raise BzrCommandError("extra argument to command %s: %s"
 
519
                              % (cmd, args[0]))
436
520
 
437
521
    return argdict
438
522
 
441
525
def apply_profiled(the_callable, *args, **kwargs):
442
526
    import hotshot
443
527
    import tempfile
444
 
    import hotshot.stats
445
528
    pffileno, pfname = tempfile.mkstemp()
446
529
    try:
447
530
        prof = hotshot.Profile(pfname)
449
532
            ret = prof.runcall(the_callable, *args, **kwargs) or 0
450
533
        finally:
451
534
            prof.close()
 
535
 
 
536
        import hotshot.stats
452
537
        stats = hotshot.stats.load(pfname)
453
 
        stats.strip_dirs()
454
 
        stats.sort_stats('cum')   # 'time'
 
538
        #stats.strip_dirs()
 
539
        stats.sort_stats('time')
455
540
        ## XXX: Might like to write to stderr or the trace file instead but
456
541
        ## print_stats seems hardcoded to stdout
457
542
        stats.print_stats(20)
 
543
 
458
544
        return ret
459
545
    finally:
460
546
        os.close(pffileno)
461
547
        os.remove(pfname)
462
548
 
463
549
 
464
 
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
465
 
    from bzrlib.lsprof import profile
466
 
    import cPickle
467
 
    ret, stats = profile(the_callable, *args, **kwargs)
468
 
    stats.sort()
469
 
    if filename is None:
470
 
        stats.pprint()
471
 
    else:
472
 
        stats.freeze()
473
 
        cPickle.dump(stats, open(filename, 'w'), 2)
474
 
        print 'Profile data written to %r.' % filename
475
 
    return ret
476
 
 
477
 
 
478
 
def get_alias(cmd, config=None):
479
 
    """Return an expanded alias, or None if no alias exists.
480
 
 
481
 
    cmd
482
 
        Command to be checked for an alias.
483
 
    config
484
 
        Used to specify an alternative config to use,
485
 
        which is especially useful for testing.
486
 
        If it is unspecified, the global config will be used.
487
 
    """
488
 
    if config is None:
489
 
        import bzrlib.config
490
 
        config = bzrlib.config.GlobalConfig()
491
 
    alias = config.get_alias(cmd)
492
 
    if (alias):
493
 
        import shlex
494
 
        return [a.decode('utf-8') for a in shlex.split(alias.encode('utf-8'))]
495
 
    return None
496
 
 
497
 
 
498
550
def run_bzr(argv):
499
551
    """Execute a command.
500
552
 
503
555
    
504
556
    argv
505
557
       The command-line arguments, without the program name from argv[0]
506
 
       These should already be decoded. All library/test code calling
507
 
       run_bzr should be passing valid strings (don't need decoding).
508
558
    
509
559
    Returns a command status or raises an exception.
510
560
 
514
564
    --no-plugins
515
565
        Do not load plugin modules at all
516
566
 
517
 
    --no-aliases
518
 
        Do not allow aliases
519
 
 
520
567
    --builtin
521
568
        Only use builtin commands.  (Plugins are still allowed to change
522
569
        other behaviour.)
523
570
 
524
571
    --profile
525
 
        Run under the Python hotshot profiler.
526
 
 
527
 
    --lsprof
528
 
        Run under the Python lsprof profiler.
 
572
        Run under the Python profiler.
529
573
    """
530
 
    argv = list(argv)
531
 
    trace.mutter("bzr arguments: %r", argv)
 
574
    # Load all of the transport methods
 
575
    import bzrlib.transport.local, bzrlib.transport.http
 
576
    
 
577
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
532
578
 
533
 
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
534
 
                opt_no_aliases = False
535
 
    opt_lsprof_file = None
 
579
    opt_profile = opt_no_plugins = opt_builtin = False
536
580
 
537
581
    # --no-plugins is handled specially at a very early stage. We need
538
582
    # to load plugins before doing other command parsing so that they
539
583
    # can override commands, but this needs to happen first.
540
584
 
541
 
    argv_copy = []
542
 
    i = 0
543
 
    while i < len(argv):
544
 
        a = argv[i]
 
585
    for a in argv:
545
586
        if a == '--profile':
546
587
            opt_profile = True
547
 
        elif a == '--lsprof':
548
 
            opt_lsprof = True
549
 
        elif a == '--lsprof-file':
550
 
            opt_lsprof = True
551
 
            opt_lsprof_file = argv[i + 1]
552
 
            i += 1
553
588
        elif a == '--no-plugins':
554
589
            opt_no_plugins = True
555
 
        elif a == '--no-aliases':
556
 
            opt_no_aliases = True
557
590
        elif a == '--builtin':
558
591
            opt_builtin = True
559
 
        elif a in ('--quiet', '-q'):
560
 
            trace.be_quiet()
561
 
        elif a.startswith('-D'):
562
 
            debug.debug_flags.add(a[2:])
563
592
        else:
564
 
            argv_copy.append(a)
565
 
        i += 1
 
593
            break
 
594
        argv.remove(a)
566
595
 
567
 
    argv = argv_copy
568
 
    if (not argv):
569
 
        from bzrlib.builtins import cmd_help
570
 
        cmd_help().run_argv_aliases([])
 
596
    if (not argv) or (argv[0] == '--help'):
 
597
        from bzrlib.help import help
 
598
        if len(argv) > 1:
 
599
            help(argv[1])
 
600
        else:
 
601
            help()
571
602
        return 0
572
603
 
573
604
    if argv[0] == '--version':
574
 
        from bzrlib.version import show_version
 
605
        from bzrlib.builtins import show_version
575
606
        show_version()
576
607
        return 0
577
608
        
578
609
    if not opt_no_plugins:
579
610
        from bzrlib.plugin import load_plugins
580
611
        load_plugins()
581
 
    else:
582
 
        from bzrlib.plugin import disable_plugins
583
 
        disable_plugins()
584
 
 
585
 
    alias_argv = None
586
 
 
587
 
    if not opt_no_aliases:
588
 
        alias_argv = get_alias(argv[0])
589
 
        if alias_argv:
590
 
            alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
591
 
            argv[0] = alias_argv.pop(0)
592
 
 
593
 
    cmd = argv.pop(0)
594
 
    # We want only 'ascii' command names, but the user may have typed
595
 
    # in a Unicode name. In that case, they should just get a
596
 
    # 'command not found' error later.
 
612
 
 
613
    cmd = str(argv.pop(0))
597
614
 
598
615
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
599
 
    if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
600
 
        run = cmd_obj.run_argv
601
 
        run_argv = [argv]
 
616
 
 
617
    if opt_profile:
 
618
        ret = apply_profiled(cmd_obj.run_argv, argv)
602
619
    else:
603
 
        run = cmd_obj.run_argv_aliases
604
 
        run_argv = [argv, alias_argv]
605
 
 
606
 
    try:
607
 
        if opt_lsprof:
608
 
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
609
 
        elif opt_profile:
610
 
            ret = apply_profiled(run, *run_argv)
611
 
        else:
612
 
            ret = run(*run_argv)
613
 
        return ret or 0
614
 
    finally:
615
 
        # reset, in case we may do other commands later within the same process
616
 
        trace.be_quiet(False)
617
 
 
618
 
def display_command(func):
619
 
    """Decorator that suppresses pipe/interrupt errors."""
620
 
    def ignore_pipe(*args, **kwargs):
621
 
        try:
622
 
            result = func(*args, **kwargs)
623
 
            sys.stdout.flush()
624
 
            return result
625
 
        except IOError, e:
626
 
            if getattr(e, 'errno', None) is None:
627
 
                raise
628
 
            if e.errno != errno.EPIPE:
629
 
                # Win32 raises IOError with errno=0 on a broken pipe
630
 
                if sys.platform != 'win32' or e.errno != 0:
631
 
                    raise
632
 
            pass
633
 
        except KeyboardInterrupt:
634
 
            pass
635
 
    return ignore_pipe
 
620
        ret = cmd_obj.run_argv(argv)
 
621
    return ret or 0
636
622
 
637
623
 
638
624
def main(argv):
639
625
    import bzrlib.ui
640
 
    from bzrlib.ui.text import TextUIFactory
641
 
    bzrlib.ui.ui_factory = TextUIFactory()
642
 
    argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
643
 
    ret = run_bzr_catch_errors(argv)
644
 
    trace.mutter("return code %d", ret)
645
 
    return ret
 
626
    bzrlib.trace.log_startup(argv)
 
627
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
 
628
 
 
629
    return run_bzr_catch_errors(argv[1:])
646
630
 
647
631
 
648
632
def run_bzr_catch_errors(argv):
649
633
    try:
650
 
        return run_bzr(argv)
651
 
        # do this here inside the exception wrappers to catch EPIPE
652
 
        sys.stdout.flush()
653
 
    except (KeyboardInterrupt, Exception), e:
654
 
        # used to handle AssertionError and KeyboardInterrupt
655
 
        # specially here, but hopefully they're handled ok by the logger now
656
 
        trace.report_exception(sys.exc_info(), sys.stderr)
657
 
        if os.environ.get('BZR_PDB'):
658
 
            print '**** entering debugger'
659
 
            import pdb
660
 
            pdb.post_mortem(sys.exc_traceback)
 
634
        try:
 
635
            try:
 
636
                return run_bzr(argv)
 
637
            finally:
 
638
                # do this here inside the exception wrappers to catch EPIPE
 
639
                sys.stdout.flush()
 
640
        #wrap common errors as CommandErrors.
 
641
        except (NotBranchError,), e:
 
642
            raise BzrCommandError(str(e))
 
643
    except BzrCommandError, e:
 
644
        # command line syntax error, etc
 
645
        log_error(str(e))
 
646
        return 1
 
647
    except BzrError, e:
 
648
        bzrlib.trace.log_exception()
 
649
        return 1
 
650
    except AssertionError, e:
 
651
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
661
652
        return 3
 
653
    except KeyboardInterrupt, e:
 
654
        bzrlib.trace.log_exception('interrupted')
 
655
        return 2
 
656
    except Exception, e:
 
657
        import errno
 
658
        if (isinstance(e, IOError) 
 
659
            and hasattr(e, 'errno')
 
660
            and e.errno == errno.EPIPE):
 
661
            bzrlib.trace.note('broken pipe')
 
662
            return 2
 
663
        else:
 
664
            bzrlib.trace.log_exception()
 
665
            return 2
662
666
 
663
667
if __name__ == '__main__':
664
668
    sys.exit(main(sys.argv))