~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

[merge] bzr.dev 2255, resolve conflicts, update copyrights

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 by Canonical Ltd
 
1
# Copyright (C) 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
28
28
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
29
29
# the profile output behind so it can be interactively examined?
30
30
 
 
31
import os
 
32
import sys
 
33
 
 
34
from bzrlib.lazy_import import lazy_import
 
35
lazy_import(globals(), """
31
36
import codecs
32
37
import errno
33
 
import os
34
38
from warnings import warn
35
 
import sys
36
39
 
37
40
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
 
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
44
57
from bzrlib.option import Option
45
 
import bzrlib.osutils
46
 
from bzrlib.symbol_versioning import (deprecated_method, zero_eight)
47
 
import bzrlib.trace
48
 
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
 
58
 
49
59
 
50
60
plugin_cmds = {}
51
61
 
66
76
        k_unsquished = k
67
77
    if k_unsquished not in plugin_cmds:
68
78
        plugin_cmds[k_unsquished] = cmd
69
 
        mutter('registered plugin command %s', k_unsquished)
 
79
        ## trace.mutter('registered plugin command %s', k_unsquished)
70
80
        if decorate and k_unsquished in builtin_command_names():
71
81
            return _builtin_commands()[k_unsquished]
72
82
    elif decorate:
74
84
        plugin_cmds[k_unsquished] = cmd
75
85
        return result
76
86
    else:
77
 
        log_error('Two plugins defined the same command: %r' % k)
78
 
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
87
        trace.log_error('Two plugins defined the same command: %r' % k)
 
88
        trace.log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
79
89
 
80
90
 
81
91
def _squish_command_name(cmd):
150
160
    if cmd_obj:
151
161
        return cmd_obj
152
162
 
153
 
    raise BzrCommandError('unknown command "%s"' % cmd_name)
 
163
    raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
154
164
 
155
165
 
156
166
class Command(object):
204
214
            replace - put in a bogus character (typically '?')
205
215
            exact - do not encode sys.stdout
206
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
 
207
223
    """
208
224
    aliases = []
209
225
    takes_args = []
222
238
 
223
239
        Maps from long option name to option object."""
224
240
        r = dict()
225
 
        r['help'] = Option.OPTIONS['help']
 
241
        r['help'] = option.Option.OPTIONS['help']
226
242
        for o in self.takes_options:
227
243
            if isinstance(o, basestring):
228
 
                o = Option.OPTIONS[o]
 
244
                o = option.Option.OPTIONS[o]
229
245
            r[o.name] = o
230
246
        return r
231
247
 
236
252
        # Originally I was using self.stdout, but that looks
237
253
        # *way* too much like sys.stdout
238
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)
239
261
            self.outf = sys.stdout
240
262
            return
241
263
 
242
 
        output_encoding = bzrlib.osutils.get_terminal_encoding()
 
264
        output_encoding = osutils.get_terminal_encoding()
243
265
 
244
266
        # use 'replace' so that we don't abort if trying to write out
245
267
        # in e.g. the default C locale.
260
282
    def run_argv_aliases(self, argv, alias_argv=None):
261
283
        """Parse the command line and run with extra aliases in alias_argv."""
262
284
        if argv is None:
263
 
            warn("Passing None for [] is deprecated from bzrlib 0.10", 
 
285
            warn("Passing None for [] is deprecated from bzrlib 0.10",
264
286
                 DeprecationWarning, stacklevel=2)
265
287
            argv = []
266
288
        args, opts = parse_args(self, argv, alias_argv)
291
313
        shell error code if not.  It's OK for this method to allow
292
314
        an exception to raise up.
293
315
        """
294
 
        raise NotImplementedError('no implementation of command %r' 
 
316
        raise NotImplementedError('no implementation of command %r'
295
317
                                  % self.name())
296
318
 
297
319
    def help(self):
316
338
            return None
317
339
 
318
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)
319
344
def parse_spec(spec):
320
345
    """
321
346
    >>> parse_spec(None)
363
388
        args = argv
364
389
 
365
390
    options, args = parser.parse_args(args)
366
 
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if 
 
391
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
367
392
                 v is not option.OptionParser.DEFAULT_VALUE])
368
393
    return args, opts
369
394
 
385
410
                argdict[argname + '_list'] = None
386
411
        elif ap[-1] == '+':
387
412
            if not args:
388
 
                raise BzrCommandError("command %r needs one or more %s"
389
 
                        % (cmd, argname.upper()))
 
413
                raise errors.BzrCommandError("command %r needs one or more %s"
 
414
                                             % (cmd, argname.upper()))
390
415
            else:
391
416
                argdict[argname + '_list'] = args[:]
392
417
                args = []
393
418
        elif ap[-1] == '$': # all but one
394
419
            if len(args) < 2:
395
 
                raise BzrCommandError("command %r needs one or more %s"
396
 
                        % (cmd, argname.upper()))
 
420
                raise errors.BzrCommandError("command %r needs one or more %s"
 
421
                                             % (cmd, argname.upper()))
397
422
            argdict[argname + '_list'] = args[:-1]
398
423
            args[:-1] = []
399
424
        else:
400
425
            # just a plain arg
401
426
            argname = ap
402
427
            if not args:
403
 
                raise BzrCommandError("command %r requires argument %s"
404
 
                        % (cmd, argname.upper()))
 
428
                raise errors.BzrCommandError("command %r requires argument %s"
 
429
                               % (cmd, argname.upper()))
405
430
            else:
406
431
                argdict[argname] = args.pop(0)
407
432
            
408
433
    if args:
409
 
        raise BzrCommandError("extra argument to command %s: %s"
410
 
                              % (cmd, args[0]))
 
434
        raise errors.BzrCommandError("extra argument to command %s: %s"
 
435
                                     % (cmd, args[0]))
411
436
 
412
437
    return argdict
413
438
 
450
475
    return ret
451
476
 
452
477
 
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)
 
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)
457
492
    if (alias):
458
 
        return alias.split(' ')
 
493
        import shlex
 
494
        return [a.decode('utf-8') for a in shlex.split(alias.encode('utf-8'))]
459
495
    return None
460
496
 
461
497
 
492
528
        Run under the Python lsprof profiler.
493
529
    """
494
530
    argv = list(argv)
 
531
    trace.mutter("bzr arguments: %r", argv)
495
532
 
496
533
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
497
534
                opt_no_aliases = False
520
557
        elif a == '--builtin':
521
558
            opt_builtin = True
522
559
        elif a in ('--quiet', '-q'):
523
 
            be_quiet()
 
560
            trace.be_quiet()
 
561
        elif a.startswith('-D'):
 
562
            debug.debug_flags.add(a[2:])
524
563
        else:
525
564
            argv_copy.append(a)
526
565
        i += 1
574
613
        return ret or 0
575
614
    finally:
576
615
        # reset, in case we may do other commands later within the same process
577
 
        be_quiet(False)
 
616
        trace.be_quiet(False)
578
617
 
579
618
def display_command(func):
580
619
    """Decorator that suppresses pipe/interrupt errors."""
602
641
    bzrlib.ui.ui_factory = TextUIFactory()
603
642
    argv = [a.decode(bzrlib.user_encoding) for a in argv[1:]]
604
643
    ret = run_bzr_catch_errors(argv)
605
 
    mutter("return code %d", ret)
 
644
    trace.mutter("return code %d", ret)
606
645
    return ret
607
646
 
608
647
 
614
653
    except (KeyboardInterrupt, Exception), e:
615
654
        # used to handle AssertionError and KeyboardInterrupt
616
655
        # specially here, but hopefully they're handled ok by the logger now
617
 
        bzrlib.trace.report_exception(sys.exc_info(), sys.stderr)
 
656
        trace.report_exception(sys.exc_info(), sys.stderr)
618
657
        if os.environ.get('BZR_PDB'):
619
658
            print '**** entering debugger'
620
659
            import pdb